django 文档参考模型

def():
				
 

Model reference
模型参考

A model is the single, definitive source of data about your data. It contains the essential fields and behaviors of the data you're storing. Generally, each model maps to a single database table.

The basics:

  • Each model is a Python class that subclasses django.db.models.Model.
  • Each attribute of the model represents a database field.
  • Model metadata (non-field information) goes in an inner class named Meta.
  • Metadata used for Django's admin site goes into an inner class named Admin.
  • With all of this, Django gives you an automatically-generated database-access API, which is explained in the Database API reference.

A companion to this document is the official repository of model examples. (In the Django source distribution, these examples are in the tests/modeltests directory.)

Quick example

This example model defines a Person, which has a first_name and last_name:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(maxlength=30)
    last_name = models.CharField(maxlength=30)

first_name and last_name are fields of the model. Each field is specified as a class attribute, and each attribute maps to a database column.

The above Person model would create a database table like this:

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

Some technical notes:

  • The name of the table, myapp_person, is automatically derived from some model metadata but can be overridden. See Table names below.
    表名 myapp_person 从模型的元数据自动产生,但也可以被重写。
  • An id field is added automatically, but this behavior can be overriden. See Automatic primary key fields below.
    id 字段是自动附加的,也可以被重写。
  • The CREATE TABLE SQL in this example is formatted using PostgreSQL syntax, but it's worth noting Django uses SQL tailored to the database backend specified in your settings file.

Fields

The most important part of a model -- and the only required part of a model -- is the list of database fields it defines. Fields are specified by class attributes.

Example:


class Musician(models.Model):
    first_name = models.CharField(maxlength=50)
    last_name = models.CharField(maxlength=50)
    instrument = models.CharField(maxlength=100)

class Album(models.Model):
    artist = models.ForeignKey(Musician) # 定义外键
    name = models.CharField(maxlength=100)
    release_date = models.DateField() # 日期字段
    num_stars = models.IntegerField()

Field name restrictions

Django places only two restrictions on model field names:

  1. A field name cannot be a Python reserved word, because that would result in a Python syntax error. For example:
    字段名不能是 Python 保留字

    class Example(models.Model):
        pass = models.IntegerField() # 'pass' is a reserved word!
    
  2. A field name cannot contain more than one underscore in a row, due to the way Django's query lookup syntax works. For example:
    字段名不能包含多于一个下划线。因为 Django 的 query 查找语法。

    class Example(models.Model):
        foo__bar = models.IntegerField() 'foo__bar' has two underscores!
    

These limitations can be worked around, though, because your field name doesn't necessarily have to match your database column name. See db_column below.

SQL reserved words, such as join, where or select, are allowed as model field names, because Django escapes all database table names and column names in every underlying SQL query. It uses the quoting syntax of your particular database engine.
SQL 保留字,如 join, where, select,可以被用作模型的字段名。

Field types

Each field in your model should be an instance of the appropriate Field class. Django uses the field class types to determine a few things:

  • The database column type (e.g. INTEGER, VARCHAR).
  • The widget to use in Django's admin interface, if you care to use it (e.g. type="text">, box with "Unknown", "Yes" and "No" choices.

PhoneNumberField
电话号码字段

A CharField that checks that the value is a valid U.S.A.-style phone number (in the format XXX-XXX-XXXX).
表示美国电话号码的格式的字段(xxx-xxx-xxxx)

PositiveIntegerField
正整数字段

Like an IntegerField, but must be positive.

PositiveSmallIntegerField
小的正整数字段

Like a PositiveIntegerField, but only allows values under a certain (database-dependent) point.
最大值取决于具体的数据库特性

SlugField

"Slug" is a newspaper term. A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They're generally used in URLs.
"Slug" 是报纸的术语。表示一个短的标签,仅包含字母,数字,下划线或连字符。一般用于 URL 中。

In the Django development version, you can specify maxlength. If maxlength is not specified, Django will use a default length of 50. In previous Django versions, there's no way to override the length of 50.
在 Django 开发版中,可指定 maxlength. 默认的长度是 50. 在低版本的 Django 中,没有办法可以覆盖长度为 50 的限制。

Implies db_index=True.
隐含 db_index=True

Accepts an extra option, prepopulate_from, which is a list of fields from which to auto-populate the slug, via JavaScript, in the object's admin form:
接受一个额外选项 prepopulate_from,用于指示在 admin 表单中的可选值。

models.SlugField(prepopulate_from=("pre_name", "name"))

prepopulate_from doesn't accept DateTimeFields.
prepopulate_from 不接受 DateTimeField 字段

The admin represents SlugField as an type="text"> (a single-line input).

SmallIntegerField
小整数字段

Like an IntegerField, but only allows values under a certain (database-dependent) point.

TextField
大文本字段

A large text field.

The admin represents this as a