模型字段参考

本文档包含 Field 类的所有 API 参考,包括 field optionsfield types

参见

若内置字段未满足需求,你可以试试 django-localflavor (文档),它包含了针对各别国家和文件的代码。

当然,你也可以简单的 编写自定义模型字段

注解

技巧性的,这些方法都被定义在 django.db.models.fields,但出于方便的目的,它们被导入 django.db.models;标准的转换是使用 from django.db import models 并利用 models.<Foo>Field 字段。

字段选项

以下参数对所以字段类型均有效,且是可选的。

null

  • Field.null
  • 如果设置为 True, 当该字段为空时,Django 会将数据库中该字段设置为 NULL,默认为 False

避免在基于字符串的字段(例如 CharFieldTextField)上使用 null。如果字符串字段的 null=True,那意味着对于“无数据”有两个可能的值:NULL 和空字符串。在大多数情况下,对于“无数据”声明两个值是赘余的,Django 的惯例是使用空字符串而不是 NULL。 一个例外是当 CharField 同时具有 unique=Trueblank=True 时。 在这种情况下,需要设置 null=True,以便在使用空白值保存多个对象时避免唯一的约束违规。

For both string-based and non-string-based fields, you will also need toset blank=True if you wish to permit empty values in forms, as thenull parameter only affects database storage(see blank).

注解

When using the Oracle database backend, the value NULL will be stored todenote the empty string regardless of this attribute.

blank

  • Field.blank
  • 如果设置为 True ,该字段允许为空。默认为 False

Note that this is different than null. null ispurely database-related, whereas blank is validation-related. Ifa field has blank=True, form validation will allow entry of an empty value.If a field has blank=False, the field will be required.

choices

  • Field.choices
  • A sequence consisting itself of iterables of exactly two items (e.g.[(A, B), (A, B) …]) to use as choices for this field. If choices aregiven, they're enforced by model validation and thedefault form widget will be a select box with these choices instead of thestandard text field.

The first element in each tuple is the actual value to be set on the model,and the second element is the human-readable name. For example:

  1. YEAR_IN_SCHOOL_CHOICES = [
  2. ('FR', 'Freshman'),
  3. ('SO', 'Sophomore'),
  4. ('JR', 'Junior'),
  5. ('SR', 'Senior'),
  6. ]

Generally, it's best to define choices inside a model class, and todefine a suitably-named constant for each value:

  1. from django.db import models
  2.  
  3. class Student(models.Model):
  4. FRESHMAN = 'FR'
  5. SOPHOMORE = 'SO'
  6. JUNIOR = 'JR'
  7. SENIOR = 'SR'
  8. YEAR_IN_SCHOOL_CHOICES = [
  9. (FRESHMAN, 'Freshman'),
  10. (SOPHOMORE, 'Sophomore'),
  11. (JUNIOR, 'Junior'),
  12. (SENIOR, 'Senior'),
  13. ]
  14. year_in_school = models.CharField(
  15. max_length=2,
  16. choices=YEAR_IN_SCHOOL_CHOICES,
  17. default=FRESHMAN,
  18. )
  19.  
  20. def is_upperclass(self):
  21. return self.year_in_school in (self.JUNIOR, self.SENIOR)

Though you can define a choices list outside of a model class and thenrefer to it, defining the choices and names for each choice inside themodel class keeps all of that information with the class that uses it,and makes the choices easy to reference (e.g, Student.SOPHOMOREwill work anywhere that the Student model has been imported).

You can also collect your available choices into named groups that canbe used for organizational purposes:

  1. MEDIA_CHOICES = [
  2. ('Audio', (
  3. ('vinyl', 'Vinyl'),
  4. ('cd', 'CD'),
  5. )
  6. ),
  7. ('Video', (
  8. ('vhs', 'VHS Tape'),
  9. ('dvd', 'DVD'),
  10. )
  11. ),
  12. ('unknown', 'Unknown'),
  13. ]

The first element in each tuple is the name to apply to the group. Thesecond element is an iterable of 2-tuples, with each 2-tuple containinga value and a human-readable name for an option. Grouped options may becombined with ungrouped options within a single list (such as theunknown option in this example).

For each model field that has choices set, Django will add amethod to retrieve the human-readable name for the field's current value. Seeget_FOO_display() in the database APIdocumentation.

Note that choices can be any sequence object — not necessarily a list ortuple. This lets you construct choices dynamically. But if you find yourselfhacking choices to be dynamic, you're probably better off usinga proper database table with a ForeignKey. choices ismeant for static data that doesn't change much, if ever.

注解

每当 choices 的顺序变动时将会创建新的迁移。

Unless blank=False is set on the field along with adefault then a label containing "————-" will be renderedwith the select box. To override this behavior, add a tuple to choicescontaining None; e.g. (None, 'Your String For Display').Alternatively, you can use an empty string instead of None where this makessense - such as on a CharField.

db_column

  • Field.db_column
  • The name of the database column to use for this field. If this isn't given,Django will use the field's name.

If your database column name is an SQL reserved word, or containscharacters that aren't allowed in Python variable names — notably, thehyphen — that's OK. Django quotes column and table names behind thescenes.

db_index

  • Field.db_index
  • If True, a database index will be created for this field.

db_tablespace

  • Field.db_tablespace
  • The name of the database tablespace to use forthis field's index, if this field is indexed. The default is the project'sDEFAULT_INDEX_TABLESPACE setting, if set, or thedb_tablespace of the model, if any. If the backend doesn'tsupport tablespaces for indexes, this option is ignored.

default

  • Field.default
  • 该字段的默认值。可以是一个值或者是个可调用的对象,如果是个可调用对象,每次实例化模型时都会调用该对象。

The default can't be a mutable object (model instance, list, set, etc.),as a reference to the same instance of that object would be used as the defaultvalue in all new model instances. Instead, wrap the desired default in acallable. For example, if you want to specify a default dict forJSONField, use a function:

  1. def contact_default():
  2. return {"email": "to1@example.com"}
  3.  
  4. contact_info = JSONField("ContactInfo", default=contact_default)

lambdas can't be used for field options like default because theycan't be serialized by migrations. See thatdocumentation for other caveats.

For fields like ForeignKey that map to model instances, defaultsshould be the value of the field they reference (pk unlessto_field is set) instead of model instances.

The default value is used when new model instances are created and a valueisn't provided for the field. When the field is a primary key, the default isalso used when the field is set to None.

editable

  • Field.editable
  • If False, the field will not be displayed in the admin or any otherModelForm. They are also skipped during modelvalidation. Default is True.

error_messages

  • Field.error_messages
  • The error_messages argument lets you override the default messages that thefield will raise. Pass in a dictionary with keys matching the error messages youwant to override.

Error message keys include null, blank, invalid, invalid_choice,unique, and unique_for_date. Additional error message keys arespecified for each field in the Field types section below.

These error messages often don't propagate to forms. See有关模型的 error_messages 的注意事项.

help_text

  • Field.help_text
  • 额外的“帮助”文本,随表单控件一同显示。即便你的字段未用于表单,它对于生成文档也是很有用的。

Note that this value is not HTML-escaped in automatically-generatedforms. This lets you include HTML in help_text if you sodesire. For example:

  1. help_text="Please use the following format: <em>YYYY-MM-DD</em>."

Alternatively you can use plain text anddjango.utils.html.escape() to escape any HTML special characters. Ensurethat you escape any help text that may come from untrusted users to avoid across-site scripting attack.

primary_key

  • Field.primary_key
  • 如果设置为 True ,将该字段设置为该模型的主键。

If you don't specify primary_key=True for any field in your model, Djangowill automatically add an AutoField to hold the primary key, so youdon't need to set primary_key=True on any of your fields unless you want tooverride the default primary-key behavior. For more, see自动设置主键.

primary_key=True implies null=False andunique=True. Only one primary key is allowed on anobject.

The primary key field is read-only. If you change the value of the primarykey on an existing object and then save it, a new object will be createdalongside the old one.

unique

  • Field.unique
  • 如果设置为 True,这个字段必须在整个表中保持值唯一。

This is enforced at the database level and by model validation. Ifyou try to save a model with a duplicate value in a uniquefield, a django.db.IntegrityError will be raised by the model'ssave() method.

This option is valid on all field types except ManyToManyField andOneToOneField.

Note that when unique is True, you don't need to specifydb_index, because unique implies the creation of an index.

unique_for_date

  • Field.unique_for_date
  • Set this to the name of a DateField or DateTimeField torequire that this field be unique for the value of the date field.

For example, if you have a field title that hasunique_for_date="pub_date", then Django wouldn't allow the entry of tworecords with the same title and pub_date.

Note that if you set this to point to a DateTimeField, only the dateportion of the field will be considered. Besides, when USE_TZ isTrue, the check will be performed in the current time zone at the time the object gets saved.

This is enforced by Model.validate_unique() during model validationbut not at the database level. If any unique_for_date constraintinvolves fields that are not part of a ModelForm (forexample, if one of the fields is listed in exclude or haseditable=False), Model.validate_unique() willskip validation for that particular constraint.

unique_for_month

  • Field.unique_for_month
  • Like unique_for_date, but requires the field to be unique withrespect to the month.

unique_for_year

verbose_name

  • Field.verbose_name
  • A human-readable name for the field. If the verbose name isn't given, Djangowill automatically create it using the field's attribute name, convertingunderscores to spaces. See Verbose field names.

validators

Registering and fetching lookups

Field implements the lookup registration API.The API can be used to customize which lookups are available for a field class, andhow lookups are fetched from a field.

字段类型

AutoField

  • class AutoField(**options)[源代码]
  • An IntegerField that automatically incrementsaccording to available IDs. You usually won't need to use this directly; aprimary key field will automatically be added to your model if you don't specifyotherwise. See 自动设置主键.

BigAutoField

  • class BigAutoField(**options)[源代码]
  • A 64-bit integer, much like an AutoField except that it isguaranteed to fit numbers from 1 to 9223372036854775807.

BigIntegerField

  • class BigIntegerField(**options)[源代码]
  • A 64-bit integer, much like an IntegerField except that it isguaranteed to fit numbers from -9223372036854775808 to9223372036854775807. The default form widget for this field is aTextInput.

BinaryField

By default, BinaryField sets editable to False, in whichcase it can't be included in a ModelForm.

Changed in Django 2.1:Older versions don't allow setting editable to True.

BinaryField has one extra optional argument:

  • BinaryField.max_length
  • The maximum length (in characters) of the field. The maximum length isenforced in Django's validation usingMaxLengthValidator.

Abusing BinaryField

Although you might think about storing files in the database, consider thatit is bad design in 99% of the cases. This field is not a replacement forproper static files handling.

BooleanField

  • class BooleanField(**options)[源代码]
  • A true/false field.

The default form widget for this field is CheckboxInput,or NullBooleanSelect if null=True.

The default value of BooleanField is None when Field.defaultisn't defined.

Changed in Django 2.1:In older versions, this field doesn't permit null=True, so you have touse NullBooleanField instead. Using the latter is now discouragedas it's likely to be deprecated in a future version of Django.

CharField

  • class CharField(max_length=None, **options)[源代码]
  • A string field, for small- to large-sized strings.

For large amounts of text, use TextField.

The default form widget for this field is a TextInput.

CharField has one extra required argument:

  • CharField.max_length
  • The maximum length (in characters) of the field. The max_length is enforcedat the database level and in Django's validation usingMaxLengthValidator.

注解

If you are writing an application that must be portable to multipledatabase backends, you should be aware that there are restrictions onmax_length for some backends. Refer to the database backendnotes for details.

DateField

  • class DateField(auto_now=False, auto_now_add=False, **options)[源代码]
  • A date, represented in Python by a datetime.date instance. Has a few extra,optional arguments:

  • DateField.auto_now

  • Automatically set the field to now every time the object is saved. Usefulfor "last-modified" timestamps. Note that the current date is _always_used; it's not just a default value that you can override.

The field is only automatically updated when calling Model.save(). The field isn't updated when making updatesto other fields in other ways such as QuerySet.update(), though you can specify a customvalue for the field in an update like that.

  • DateField.auto_now_add
  • Automatically set the field to now when the object is first created. Usefulfor creation of timestamps. Note that the current date is always used;it's not just a default value that you can override. So even if youset a value for this field when creating the object, it will be ignored.If you want to be able to modify this field, set the following instead ofauto_now_add=True:

The options auto_now_add, auto_now, and default are mutually exclusive.Any combination of these options will result in an error.

注解

As currently implemented, setting auto_now or auto_now_add toTrue will cause the field to have editable=False and blank=Trueset.

注解

The auto_now and auto_now_add options will always use the date inthe default timezone at the moment ofcreation or update. If you need something different, you may want toconsider simply using your own callable default or overriding save()instead of using auto_now or auto_now_add; or using aDateTimeField instead of a DateField and deciding how to handle theconversion from datetime to date at display time.

DateTimeField

  • class DateTimeField(auto_now=False, auto_now_add=False, **options)[源代码]
  • A date and time, represented in Python by a datetime.datetime instance.Takes the same extra arguments as DateField.

The default form widget for this field is a singleTextInput. The admin uses two separateTextInput widgets with JavaScript shortcuts.

DecimalField

  • class DecimalField(max_digits=None, decimal_places=None, **options)[源代码]
  • A fixed-precision decimal number, represented in Python by aDecimal instance. It validates the input usingDecimalValidator.

Has two required arguments:

  • DecimalField.max_digits
  • The maximum number of digits allowed in the number. Note that this numbermust be greater than or equal to decimal_places.

  • DecimalField.decimal_places

  • The number of decimal places to store with the number.

For example, to store numbers up to 999 with a resolution of 2 decimalplaces, you'd use:

  1. models.DecimalField(..., max_digits=5, decimal_places=2)

And to store numbers up to approximately one billion with a resolution of 10decimal places:

  1. models.DecimalField(..., max_digits=19, decimal_places=10)

The default form widget for this field is a NumberInputwhen localize is False orTextInput otherwise.

注解

For more information about the differences between theFloatField and DecimalField classes, pleasesee FloatField vs. DecimalField. Youshould also be aware of SQLite limitationsof decimal fields.

DurationField

  • class DurationField(**options)[源代码]
  • A field for storing periods of time - modeled in Python bytimedelta. When used on PostgreSQL, the data typeused is an interval and on Oracle the data type is INTERVAL DAY(9) TOSECOND(6). Otherwise a bigint of microseconds is used.

注解

Arithmetic with DurationField works in most cases. However on alldatabases other than PostgreSQL, comparing the value of a DurationFieldto arithmetic on DateTimeField instances will not work as expected.

EmailField

FileField

  • class FileField(upload_to=None, max_length=100, **options)[源代码]
  • A file-upload field.

注解

The primary_key argument isn't supported and will raise an error ifused.

Has two optional arguments:

  • FileField.upload_to
  • This attribute provides a way of setting the upload directory and file name,and can be set in two ways. In both cases, the value is passed to theStorage.save() method.

If you specify a string value, it may contain strftime()formatting, which will be replaced by the date/time of the file upload (sothat uploaded files don't fill up the given directory). For example:

  1. class MyModel(models.Model):
  2. # file will be uploaded to MEDIA_ROOT/uploads
  3. upload = models.FileField(upload_to='uploads/')
  4. # or...
  5. # file will be saved to MEDIA_ROOT/uploads/2015/01/30
  6. upload = models.FileField(upload_to='uploads/%Y/%m/%d/')

If you are using the defaultFileSystemStorage, the string valuewill be appended to your MEDIA_ROOT path to form the location onthe local filesystem where uploaded files will be stored. If you are usinga different storage, check that storage's documentation to see how ithandles upload_to.

upload_to may also be a callable, such as a function. This will becalled to obtain the upload path, including the filename. This callable mustaccept two arguments and return a Unix-style path (with forward slashes)to be passed along to the storage system. The two arguments are:

Argument描述instanceAn instance of the model where theFileField is defined. More specifically,this is the particular instance where thecurrent file is being attached.

In most cases, this object will not have beensaved to the database yet, so if it uses thedefault AutoField, it might not yet have avalue for its primary key field.filenameThe filename that was originally given to thefile. This may or may not be taken into accountwhen determining the final destination path.

例子:

  1. def user_directory_path(instance, filename):
  2. # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>
  3. return 'user_{0}/{1}'.format(instance.user.id, filename)
  4.  
  5. class MyModel(models.Model):
  6. upload = models.FileField(upload_to=user_directory_path)
  • FileField.storage
  • A storage object, which handles the storage and retrieval of yourfiles. See 管理文件 for details on how to provide this object.

The default form widget for this field is aClearableFileInput.

Using a FileField or an ImageField (see below) in a modeltakes a few steps:

  • 在你的 setting 文件中,你需要定义:setting: MEDIA_ROOT 作为 Django 存储上传文件目录的完整路径。(为了提高性能,这些文件不会储存在数据库中)定义: setting: MEDIA_URL 作为该目录的基本公共 URL, 确保该目录能够被 Web 服务器的是用户写入。
  • Add the FileField or ImageField to your model, definingthe upload_to option to specify a subdirectory ofMEDIA_ROOT to use for uploaded files.
  • All that will be stored in your database is a path to the file(relative to MEDIA_ROOT). You'll most likely want to use theconvenience url attributeprovided by Django. For example, if your ImageField is calledmug_shot, you can get the absolute path to your image in a template with{{ object.mug_shot.url }}.For example, say your MEDIA_ROOT is set to '/home/media', andupload_to is set to 'photos/%Y/%m/%d'. The '%Y/%m/%d'part of upload_to is strftime() formatting;'%Y' is the four-digit year, '%m' is the two-digit month and '%d' isthe two-digit day. If you upload a file on Jan. 15, 2007, it will be saved inthe directory /home/media/photos/2007/01/15.

If you wanted to retrieve the uploaded file's on-disk filename, or the file'ssize, you could use the name andsize attributes respectively; for moreinformation on the available attributes and methods, see theFile class reference and the 管理文件topic guide.

注解

The file is saved as part of saving the model in the database, so the actualfile name used on disk cannot be relied on until after the model has beensaved.

The uploaded file's relative URL can be obtained using theurl attribute. Internally,this calls the url() method of theunderlying Storage class.

Note that whenever you deal with uploaded files, you should pay close attentionto where you're uploading them and what type of files they are, to avoidsecurity holes. Validate all uploaded files so that you're sure the files arewhat you think they are. For example, if you blindly let somebody upload files,without validation, to a directory that's within your Web server's documentroot, then somebody could upload a CGI or PHP script and execute that script byvisiting its URL on your site. Don't allow that.

Also note that even an uploaded HTML file, since it can be executed by thebrowser (though not by the server), can pose security threats that areequivalent to XSS or CSRF attacks.

FileField instances are created in your database as varcharcolumns with a default max length of 100 characters. As with other fields, youcan change the maximum length using the max_length argument.

FileFieldFieldFile

  • class FieldFile[源代码]
  • When you access a FileField on a model, you aregiven an instance of FieldFile as a proxy for accessing the underlyingfile.

The API of FieldFile mirrors that of File,with one key difference: The object wrapped by the class is not necessarily awrapper around Python's built-in file object. Instead, it is a wrapper aroundthe result of the Storage.open()method, which may be a File object, or it may be acustom storage's implementation of the File API.

In addition to the API inherited from File such asread() and write(), FieldFile includes several methods thatcan be used to interact with the underlying file:

警告

Two methods of this class, save() anddelete(), default to saving the model object of theassociated FieldFile in the database.

  • FieldFile.name
  • The name of the file including the relative path from the root of theStorage of the associatedFileField.

  • FieldFile.size

  • The result of the underlying Storage.size() method.

  • FieldFile.url

  • A read-only property to access the file's relative URL by calling theurl() method of the underlyingStorage class.

  • FieldFile.open(mode='rb')[源代码]

  • Opens or reopens the file associated with this instance in the specifiedmode. Unlike the standard Python open() method, it doesn't return afile descriptor.

Since the underlying file is opened implicitly when accessing it, it may beunnecessary to call this method except to reset the pointer to the underlyingfile or to change the mode.

  • FieldFile.close()[源代码]
  • Behaves like the standard Python file.close() method and closes the fileassociated with this instance.

  • FieldFile.save(name, content, save=True)[源代码]

  • This method takes a filename and file contents and passes them to the storageclass for the field, then associates the stored file with the model field.If you want to manually associate file data withFileField instances on your model, the save()method is used to persist that file data.

Takes two required arguments: name which is the name of the file, andcontent which is an object containing the file's contents. Theoptional save argument controls whether or not the model instance issaved after the file associated with this field has been altered. Defaults toTrue.

Note that the content argument should be an instance ofdjango.core.files.File, not Python's built-in file object.You can construct a File from an existingPython file object like this:

  1. from django.core.files import File
  2. # Open an existing file using Python's built-in open()
  3. f = open('/path/to/hello.world')
  4. myfile = File(f)

Or you can construct one from a Python string like this:

  1. from django.core.files.base import ContentFile
  2. myfile = ContentFile("hello world")

For more information, see 管理文件.

  • FieldFile.delete(save=True)[源代码]
  • Deletes the file associated with this instance and clears all attributes onthe field. Note: This method will close the file if it happens to be open whendelete() is called.

The optional save argument controls whether or not the model instance issaved after the file associated with this field has been deleted. Defaults toTrue.

Note that when a model is deleted, related files are not deleted. If you needto cleanup orphaned files, you'll need to handle it yourself (for instance,with a custom management command that can be run manually or scheduled to runperiodically via e.g. cron).

FilePathField

  • class FilePathField(path=None, match=None, recursive=False, max_length=100, **options)[源代码]
  • A CharField whose choices are limited to the filenames in a certaindirectory on the filesystem. Has three special arguments, of which the first isrequired:

  • FilePathField.path

  • Required. The absolute filesystem path to a directory from which thisFilePathField should get its choices. Example: "/home/images".

  • FilePathField.match

  • Optional. A regular expression, as a string, that FilePathFieldwill use to filter filenames. Note that the regex will be applied to thebase filename, not the full path. Example: "foo.*.txt$", which willmatch a file called foo23.txt but not bar.txt or foo23.png.

  • FilePathField.recursive

  • Optional. Either True or False. Default is False. Specifieswhether all subdirectories of path should be included

  • FilePathField.allow_files

  • Optional. Either True or False. Default is True. Specifieswhether files in the specified location should be included. Either this orallow_folders must be True.

  • FilePathField.allow_folders

  • Optional. Either True or False. Default is False. Specifieswhether folders in the specified location should be included. Either thisor allow_files must be True.

当然,这些参数能够同时使用。

The one potential gotcha is that match applies to thebase filename, not the full path. So, this example:

  1. FilePathField(path="/home/images", match="foo.*", recursive=True)

…will match /home/images/foo.png but not /home/images/foo/bar.pngbecause the match applies to the base filename(foo.png and bar.png).

FilePathField instances are created in your database as varcharcolumns with a default max length of 100 characters. As with other fields, youcan change the maximum length using the max_length argument.

FloatField

  • class FloatField(**options)[源代码]
  • A floating-point number represented in Python by a float instance.

The default form widget for this field is a NumberInputwhen localize is False orTextInput otherwise.

FloatField vs. DecimalField

The FloatField class is sometimes mixed up with theDecimalField class. Although they both represent real numbers, theyrepresent those numbers differently. FloatField uses Python's floattype internally, while DecimalField uses Python's Decimal type. Forinformation on the difference between the two, see Python's documentationfor the decimal module.

ImageField

  • class ImageField(upload_to=None, height_field=None, width_field=None, max_length=100, **options)[源代码]
  • Inherits all attributes and methods from FileField, but alsovalidates that the uploaded object is a valid image.

In addition to the special attributes that are available for FileField,an ImageField also has height and width attributes.

To facilitate querying on those attributes, ImageField has two extraoptional arguments:

  • ImageField.height_field
  • Name of a model field which will be auto-populated with the height of theimage each time the model instance is saved.

  • ImageField.width_field

  • Name of a model field which will be auto-populated with the width of theimage each time the model instance is saved.

Requires the Pillow library.

ImageField instances are created in your database as varcharcolumns with a default max length of 100 characters. As with other fields, youcan change the maximum length using the max_length argument.

The default form widget for this field is aClearableFileInput.

IntegerField

  • class IntegerField(**options)[源代码]
  • An integer. Values from -2147483648 to 2147483647 are safe in alldatabases supported by Django.

It uses MinValueValidator andMaxValueValidator to validate the input basedon the values that the default database supports.

The default form widget for this field is a NumberInputwhen localize is False orTextInput otherwise.

GenericIPAddressField

  • class GenericIPAddressField(protocol='both', unpack_ipv4=False, **options)[源代码]
  • An IPv4 or IPv6 address, in string format (e.g. 192.0.2.30 or2a02:42fe::4). The default form widget for this field is aTextInput.

The IPv6 address normalization follows RFC 4291#section-2.2 section 2.2,including using the IPv4 format suggested in paragraph 3 of that section, like::ffff:192.0.2.0. For example, 2001:0::0:01 would be normalized to2001::1, and ::ffff:0a0a:0a0a to ::ffff:10.10.10.10. All charactersare converted to lowercase.

  • GenericIPAddressField.protocol
  • Limits valid inputs to the specified protocol.Accepted values are 'both' (default), 'IPv4'or 'IPv6'. Matching is case insensitive.

  • GenericIPAddressField.unpack_ipv4

  • Unpacks IPv4 mapped addresses like ::ffff:192.0.2.1.If this option is enabled that address would be unpacked to192.0.2.1. Default is disabled. Can only be usedwhen protocol is set to 'both'.

If you allow for blank values, you have to allow for null values since blankvalues are stored as null.

NullBooleanField

  • class NullBooleanField(**options)[源代码]
  • Like BooleanField with null=True. Use that instead of this fieldas it's likely to be deprecated in a future version of Django.

PositiveIntegerField

  • class PositiveIntegerField(**options)[源代码]
  • Like an IntegerField, but must be either positive or zero (0).Values from 0 to 2147483647 are safe in all databases supported byDjango. The value 0 is accepted for backward compatibility reasons.

PositiveSmallIntegerField

  • class PositiveSmallIntegerField(**options)[源代码]
  • Like a PositiveIntegerField, but only allows values under a certain(database-dependent) point. Values from 0 to 32767 are safe in alldatabases supported by Django.

SlugField

  • class SlugField(max_length=50, **options)[源代码]
  • Slug is a newspaper term. A slug is a short label for something,containing only letters, numbers, underscores or hyphens. They're generally usedin URLs.

Like a CharField, you can specify max_length (read the noteabout database portability and max_length in that section,too). If max_length is not specified, Django will use adefault length of 50.

Implies setting Field.db_index to True.

It is often useful to automatically prepopulate a SlugField based on the valueof some other value. You can do this automatically in the admin usingprepopulated_fields.

It uses validate_slug orvalidate_unicode_slug for validation.

  • SlugField.allow_unicode
  • If True, the field accepts Unicode letters in addition to ASCIIletters. Defaults to False.

SmallIntegerField

  • class SmallIntegerField(**options)[源代码]
  • Like an IntegerField, but only allows values under a certain(database-dependent) point. Values from -32768 to 32767 are safe in alldatabases supported by Django.

TextField

  • class TextField(**options)[源代码]
  • A large text field. The default form widget for this field is aTextarea.

If you specify a max_length attribute, it will be reflected in theTextarea widget of the auto-generated form field.However it is not enforced at the model or database level. Use aCharField for that.

TimeField

  • class TimeField(auto_now=False, auto_now_add=False, **options)[源代码]
  • A time, represented in Python by a datetime.time instance. Accepts the sameauto-population options as DateField.

The default form widget for this field is a TextInput.The admin adds some JavaScript shortcuts.

URLField

The default form widget for this field is a TextInput.

Like all CharField subclasses, URLField takes the optionalmax_length argument. If you don't specifymax_length, a default of 200 is used.

UUIDField

  • class UUIDField(**options)[源代码]
  • A field for storing universally unique identifiers. Uses Python'sUUID class. When used on PostgreSQL, this stores in auuid datatype, otherwise in a char(32).

Universally unique identifiers are a good alternative to AutoField forprimary_key. The database will not generate the UUID for you, soit is recommended to use default:

  1. import uuid
  2. from django.db import models
  3.  
  4. class MyUUIDModel(models.Model):
  5. id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
  6. # other fields

Note that a callable (with the parentheses omitted) is passed to default,not an instance of UUID.

关联关系字段

Django也定义了一组代表关系的字段。

ForeignKey

  • class ForeignKey(to, on_delete, **options)[源代码]
  • 多对一的关系。需要两个位置参数:被关联的类和 on_delete 选项

如果要创建一个递归关系 — 一个与其自身有多对一关系的对象 — 则使用 models.ForeignKey('self', on_delete=models.CASCADE)

If you need to create a relationship on a model that has not yet been defined,you can use the name of the model, rather than the model object itself:

  1. from django.db import models
  2.  
  3. class Car(models.Model):
  4. manufacturer = models.ForeignKey(
  5. 'Manufacturer',
  6. on_delete=models.CASCADE,
  7. )
  8. # ...
  9.  
  10. class Manufacturer(models.Model):
  11. # ...
  12. pass

Relationships defined this way on abstract models are resolved when the model is subclassed as aconcrete model and are not relative to the abstract model's app_label:

products/models.py

  1. from django.db import models
  2.  
  3. class AbstractCar(models.Model):
  4. manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
  5.  
  6. class Meta:
  7. abstract = True

production/models.py

  1. from django.db import models
  2. from products.models import AbstractCar
  3.  
  4. class Manufacturer(models.Model):
  5. pass
  6.  
  7. class Car(AbstractCar):
  8. pass
  9.  
  10. # Car.manufacturer will point to `production.Manufacturer` here.

To refer to models defined in another application, you can explicitly specifya model with the full application label. For example, if the Manufacturermodel above is defined in another application called production, you'dneed to use:

  1. class Car(models.Model):
  2. manufacturer = models.ForeignKey(
  3. 'production.Manufacturer',
  4. on_delete=models.CASCADE,
  5. )

This sort of reference, called a lazy relationship, can be useful whenresolving circular import dependencies between two applications.

A database index is automatically created on the ForeignKey. You candisable this by setting db_index to False. You may want toavoid the overhead of an index if you are creating a foreign key forconsistency rather than joins, or if you will be creating an alternative indexlike a partial or multiple column index.

数据库表现

Behind the scenes, Django appends "_id" to the field name to create itsdatabase column name. In the above example, the database table for the Carmodel will have a manufacturer_id column. (You can change this explicitly byspecifying db_column) However, your code should never have todeal with the database column name, unless you write custom SQL. You'll alwaysdeal with the field names of your model object.

参数

ForeignKey accepts other arguments that define the details of how therelation works.

  • ForeignKey.on_delete
  • When an object referenced by a ForeignKey is deleted, Django willemulate the behavior of the SQL constraint specified by theon_delete argument. For example, if you have a nullableForeignKey and you want it to be set null when the referencedobject is deleted:
  1. user = models.ForeignKey(
  2. User,
  3. models.SET_NULL,
  4. blank=True,
  5. null=True,
  6. )

on_delete doesn't create a SQL constraint in the database. Support fordatabase-level cascade options may be implemented later.

The possible values for on_delete are found indjango.db.models:

    • CASCADE[源代码]
    • Cascade deletes. Django emulates the behavior of the SQL constraint ONDELETE CASCADE and also deletes the object containing the ForeignKey.

Model.delete() isn't called on related models, but thepre_delete andpost_delete signals are sent for alldeleted objects.

  1. from django.conf import settings
  2. from django.contrib.auth import get_user_model
  3. from django.db import models
  4.  
  5. def get_sentinel_user():
  6. return get_user_model().objects.get_or_create(username='deleted')[0]
  7.  
  8. class MyModel(models.Model):
  9. user = models.ForeignKey(
  10. settings.AUTH_USER_MODEL,
  11. on_delete=models.SET(get_sentinel_user),
  12. )
    • DO_NOTHING[源代码]
    • Take no action. If your database backend enforces referentialintegrity, this will cause an IntegrityError unlessyou manually add an SQL ON DELETE constraint to the database field.
  • ForeignKey.limit_choices_to

  • Sets a limit to the available choices for this field when this field isrendered using a ModelForm or the admin (by default, all objectsin the queryset are available to choose). Either a dictionary, aQ object, or a callable returning adictionary or Q object can be used.

例子:

  1. staff_member = models.ForeignKey(
  2. User,
  3. on_delete=models.CASCADE,
  4. limit_choices_to={'is_staff': True},
  5. )

causes the corresponding field on the ModelForm to list only Usersthat have is_staff=True. This may be helpful in the Django admin.

The callable form can be helpful, for instance, when used in conjunctionwith the Python datetime module to limit selections by date range. Forexample:

  1. def limit_pub_date_choices():
  2. return {'pub_date__lte': datetime.date.utcnow()}
  3.  
  4. limit_choices_to = limit_pub_date_choices

If limit_choices_to is or returns a Q object, which is useful for complex queries, then it will only have an effect on the choicesavailable in the admin when the field is not listed inraw_id_fields in theModelAdmin for the model.

注解

If a callable is used for limit_choices_to, it will be invokedevery time a new form is instantiated. It may also be invoked when amodel is validated, for example by management commands or the admin.The admin constructs querysets to validate its form inputs in variousedge cases multiple times, so there is a possibility your callable maybe invoked several times.

  • ForeignKey.related_name
  • The name to use for the relation from the related object back to this one.It's also the default value for related_query_name (the name to usefor the reverse filter name from the target model). See the relatedobjects documentation for a full explanationand example. Note that you must set this value when defining relations onabstract models; and when you do sosome special syntax is available.

If you'd prefer Django not to create a backwards relation, setrelated_name to '+' or end it with '+'. For example, this willensure that the User model won't have a backwards relation to thismodel:

  1. user = models.ForeignKey(
  2. User,
  3. on_delete=models.CASCADE,
  4. related_name='+',
  5. )
  • ForeignKey.related_query_name
  • The name to use for the reverse filter name from the target model. Itdefaults to the value of related_name ordefault_related_name if set, otherwise itdefaults to the name of the model:
  1. # Declare the ForeignKey with related_query_name
  2. class Tag(models.Model):
  3. article = models.ForeignKey(
  4. Article,
  5. on_delete=models.CASCADE,
  6. related_name="tags",
  7. related_query_name="tag",
  8. )
  9. name = models.CharField(max_length=255)
  10.  
  11. # That's now the name of the reverse filter
  12. Article.objects.filter(tag__name="important")

Like related_name, related_query_name supports app label andclass interpolation via some special syntax.

  • ForeignKey.to_field
  • The field on the related object that the relation is to. By default, Djangouses the primary key of the related object. If you reference a differentfield, that field must have unique=True.

  • ForeignKey.db_constraint

  • 控制是否中介模型中外键的约束应该在数据库中被创建。默认值是True, 而且这几乎确定就是你需要的功能。将这个设为False会损坏数据的完整性。即便如此,一下场景一可能需要这样做

    • 你有无效的冗余数据
    • 你正在共享你的数据库If this is set to False, accessing a related object that doesn't existwill raise its DoesNotExist exception.
  • ForeignKey.swappable

  • Controls the migration framework's reaction if this ForeignKeyis pointing at a swappable model. If it is True - the default -then if the ForeignKey is pointing at a model which matchesthe current value of settings.AUTH_USER_MODEL (or another swappablemodel setting) the relationship will be stored in the migration usinga reference to the setting, not to the model directly.

You only want to override this to be False if you are sure yourmodel should always point towards the swapped-in model - for example,if it is a profile model designed specifically for your custom user model.

Setting it to False does not mean you can reference a swappable modeleven if it is swapped out - False just means that the migrations madewith this ForeignKey will always reference the exact model you specify(so it will fail hard if the user tries to run with a User model you don'tsupport, for example).

如果不确定,就保留它在默认为True的状态。

ManyToManyField

  • class ManyToManyField(to, **options)[源代码]
  • A many-to-many relationship. Requires a positional argument: the class towhich the model is related, which works exactly the same as it does forForeignKey, including recursive andlazy relationships.

通过这个字段的:class:~django.db.models.fields.related.RelatedManager,关联的对象可以被添加,删除,或者创建。

数据库表现

Behind the scenes, Django creates an intermediary join table to represent themany-to-many relationship. By default, this table name is generated using thename of the many-to-many field and the name of the table for the model thatcontains it. Since some databases don't support table names above a certainlength, these table names will be automatically truncated and a uniqueness hashwill be used, e.g. author_books_9cdf. You can manually provide the name ofthe join table using the db_table option.

参数

ManyToManyField accepts an extra set of arguments — all optional —that control how the relationship functions.

limit_choices_to has no effect when used on a ManyToManyField with acustom intermediate table specified using thethrough parameter.

  • ManyToManyField.symmetrical
  • 仅在定义自身为多对多字段关系时。考虑下面这个模型
  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. friends = models.ManyToManyField("self")

当django处理这个模型时,它会做如此定义, 它对自身有一个:class:`ManyToManyField`的关系,并且作为结果,它没有添加一个“person_set”属性到person这个类中。而是, 这个多对多字段关系被认为是对称的——即,如果我是你的朋友,那么你也是我的朋友。

If you do not want symmetry in many-to-many relationships with self, setsymmetrical to False. This will force Django toadd the descriptor for the reverse relationship, allowingManyToManyField relationships to be non-symmetrical.

  • ManyToManyField.through
  • Django will automatically generate a table to manage many-to-manyrelationships. However, if you want to manually specify the intermediarytable, you can use the through option to specifythe Django model that represents the intermediate table that you want touse.

The most common use for this option is when you want to associateextra data with a many-to-many relationship.

If you don't specify an explicit through model, there is still animplicit through model class you can use to directly access the tablecreated to hold the association. It has three fields to link the models.

如果源和目标模型不同,下面的字段会生成:

  • id: the primary key of the relation.
  • <containing_model>_id: the id of the model that declares theManyToManyField.
  • <other_model>_id: the id of the model that theManyToManyField points to.如果ManyToManyField指向的来源和目标是相同的模型, 下面的字段会生成:

  • id: the primary key of the relation.

  • from_<model>_id: the id of the instance which points at themodel (i.e. the source instance).
  • to_<model>_id: the id of the instance to which the relationshippoints (i.e. the target model instance).这个类可以用来查询联接给出模型实例的记录,使用方式和普通模型类似。
  • ManyToManyField.through_fields
  • 仅在明确给出一个自定义中间模型时使用。django将会正常地的决定使用中间模型的那些字段来自动地建立一个多对多的关系。然而,考虑下面的模型。
  1. from django.db import models
  2.  
  3. class Person(models.Model):
  4. name = models.CharField(max_length=50)
  5.  
  6. class Group(models.Model):
  7. name = models.CharField(max_length=128)
  8. members = models.ManyToManyField(
  9. Person,
  10. through='Membership',
  11. through_fields=('group', 'person'),
  12. )
  13.  
  14. class Membership(models.Model):
  15. group = models.ForeignKey(Group, on_delete=models.CASCADE)
  16. person = models.ForeignKey(Person, on_delete=models.CASCADE)
  17. inviter = models.ForeignKey(
  18. Person,
  19. on_delete=models.CASCADE,
  20. related_name="membership_invites",
  21. )
  22. invite_reason = models.CharField(max_length=64)

Membership 有两个外键Personpersoninviter),这使得联接关系显的歧义,django并不知道使用哪一个。这个例子中,你必须显式的指定Django应该使用哪个外键, 通过through_fields, 就想上例中一样。

through_fields接受一个2元组(fiels1fields2),其中fields1是多对多关系字段被定义的那个模型的外键名称(本例中的group), fields2是目标模型的外键名称(本例中的person)。

当你的中介表中有不止一个外键指向任一(或均)参与多对多关系的模型时, 你必须指定through_fields。这通用适用于:ref:_递归关系 <recursive-relationships>_[]($ab1c3b248dd32719.md#id1)中,场景是使用一个中介表并且不止两个外键指向同一个模型时,或者你需要显式地指定Django应该使用哪两个。

Recursive relationships using an intermediary model are always defined asnon-symmetrical — that is, with symmetrical=False— therefore, there is the concept of a "source" and a "target". In thatcase 'field1' will be treated as the "source" of the relationship and'field2' as the "target".

  • ManyToManyField.db_table
  • The name of the table to create for storing the many-to-many data. If thisis not provided, Django will assume a default name based upon the names of:the table for the model defining the relationship and the name of the fielditself.

  • ManyToManyField.db_constraint

  • 控制是否中介模型中外键的约束应该在数据库中被创建。默认值是True, 而且这几乎确定就是你需要的功能。将这个设为False会损坏数据的完整性。即便如此,一下场景一可能需要这样做:

    • 你有无效的冗余数据
    • 你正在共享你的数据库同时传递"db_constraint"和“through”会引发错误。
  • ManyToManyField.swappable

  • Controls the migration framework's reaction if this ManyToManyFieldis pointing at a swappable model. If it is True - the default -then if the ManyToManyField is pointing at a model which matchesthe current value of settings.AUTH_USER_MODEL (or another swappablemodel setting) the relationship will be stored in the migration usinga reference to the setting, not to the model directly.

You only want to override this to be False if you are sure yourmodel should always point towards the swapped-in model - for example,if it is a profile model designed specifically for your custom user model.

如果不确定,就保留它在默认为True的状态。

ManyToManyField does not support validators.

null has no effect since there is no way to require arelationship at the database level.

OneToOneField

  • class OneToOneField(to, on_delete, parent_link=False, **options)[源代码]
  • A one-to-one relationship. Conceptually, this is similar to aForeignKey with unique=True, but the"reverse" side of the relation will directly return a single object.

This is most useful as the primary key of a model which "extends"another model in some way; 多表继承 isimplemented by adding an implicit one-to-one relation from the childmodel to the parent model, for example.

One positional argument is required: the class to which the model will berelated. This works exactly the same as it does for ForeignKey,including all the options regarding recursiveand lazy relationships.

If you do not specify the related_name argument for theOneToOneField, Django will use the lowercase name of the current model asdefault value.

With the following example:

  1. from django.conf import settings
  2. from django.db import models
  3.  
  4. class MySpecialUser(models.Model):
  5. user = models.OneToOneField(
  6. settings.AUTH_USER_MODEL,
  7. on_delete=models.CASCADE,
  8. )
  9. supervisor = models.OneToOneField(
  10. settings.AUTH_USER_MODEL,
  11. on_delete=models.CASCADE,
  12. related_name='supervisor_of',
  13. )

your resulting User model will have the following attributes:

  1. >>> user = User.objects.get(pk=1)
  2. >>> hasattr(user, 'myspecialuser')
  3. True
  4. >>> hasattr(user, 'supervisor_of')
  5. True

A DoesNotExist exception is raised when accessing the reverse relationshipif an entry in the related table doesn't exist. For example, if a user doesn'thave a supervisor designated by MySpecialUser:

  1. >>> user.supervisor_of
  2. Traceback (most recent call last):
  3. ...
  4. DoesNotExist: User matching query does not exist.

Additionally, OneToOneField accepts all of the extra argumentsaccepted by ForeignKey, plus one extra argument:

  • OneToOneField.parent_link
  • When True and used in a model which inherits from anotherconcrete model, indicates that this field should be used as thelink back to the parent class, rather than the extraOneToOneField which would normally be implicitly created bysubclassing.

See One-to-one relationships for usageexamples of OneToOneField.

Field API reference

A field is thus a fundamental piece in different Django APIs, notably,models and querysets.

In models, a field is instantiated as a class attribute and represents aparticular table column, see 模型. It has attributessuch as null and unique, and methods that Django uses tomap the field value to database-specific values.

A Field is a subclass ofRegisterLookupMixin and thus bothTransform andLookup can be registered on it to be usedin QuerySets (e.g. field_name__exact="foo"). All built-inlookups are registered by default.

All of Django's built-in fields, such as CharField, are particularimplementations of Field. If you need a custom field, you can eithersubclass any of the built-in fields or write a Field from scratch. Ineither case, see 编写自定义模型字段(model fields).

The description can be of the form:

  1. description = _("String (up to %(max_length)s)")

where the arguments are interpolated from the field's dict.

To map a Field to a database-specific type, Django exposes severalmethods:

  • get_internal_type()[源代码]
  • Returns a string naming this field for backend specific purposes.By default, it returns the class name.

See 仿造内置字段类型 for usage in custom fields.

  • dbtype(_connection)[源代码]
  • Returns the database column data type for the Field, takinginto account the connection.

See 自定义数据库类型 for usage in custom fields.

  • reldb_type(_connection)[源代码]
  • Returns the database column data type for fields such as ForeignKeyand OneToOneField that point to the Field, takinginto account the connection.

See 自定义数据库类型 for usage in custom fields.

There are three main situations where Django needs to interact with thedatabase backend and fields:

  • when it queries the database (Python value -> database backend value)
  • when it loads data from the database (database backend value -> Pythonvalue)
  • when it saves to the database (Python value -> database backend value)When querying, get_db_prep_value() and get_prep_value() are used:

  • getprep_value(_value)[源代码]

  • value is the current value of the model's attribute, and the methodshould return data in a format that has been prepared for use as aparameter in a query.

See 将 Python 转为查询值 for usage.

  • getdb_prep_value(_value, connection, prepared=False)[源代码]
  • Converts value to a backend-specific value. By default it returnsvalue if prepared=True and get_prep_value() if isFalse.

See 将查询值转为数据库值 for usage.

When loading data, from_db_value() is used:

  • fromdb_value(_value, expression, connection)
  • Converts a value as returned by the database to a Python object. It isthe reverse of get_prep_value().

This method is not used for most built-in fields as the databasebackend already returns the correct Python type, or the backend itselfdoes the conversion.

See 将值转为 Python 对象 for usage.

注解

For performance reasons, from_db_value is not implemented as ano-op on fields which do not require it (all Django fields).Consequently you may not call super in your definition.

When saving, pre_save() and get_db_prep_save() are used:

model_instance is the instance this field belongs to and addis whether the instance is being saved to the database for the firsttime.

It should return the value of the appropriate attribute frommodel_instance for this field. The attribute name is inself.attname (this is set up by Field).

See 在保存前预处理数值 for usage.

Fields often receive their values as a different type, either fromserialization or from forms.

See 将值转为 Python 对象 for usage.

Besides saving to the database, the field also needs to know how toserialize its value:

  • valuefrom_object(_obj)[源代码]
  • Returns the field's value for the given model instance.

This method is often used by value_to_string().

  • valueto_string(_obj)[源代码]
  • Converts obj to a string. Used to serialize the value of the field.

See 为序列化转换字段数据 for usage.

When using model forms, the Fieldneeds to know which form field it should be represented by:

By default, if both form_class and choices_form_class areNone, it uses CharField. If the field haschoices and choices_form_classisn't specified, it uses TypedChoiceField.

See 为模型字段指定表单字段 for usage.

  • deconstruct()[源代码]
  • Returns a 4-tuple with enough information to recreate the field:

    • The name of the field on the model.
    • The import path of the field (e.g. "django.db.models.IntegerField").This should be the most portable version, so less specific may be better.
    • A list of positional arguments.
    • A dict of keyword arguments.This method must be added to fields prior to 1.7 to migrate its datausing Migrations.

Field attribute reference

Every Field instance contains several attributes that allowintrospecting its behavior. Use these attributes instead of isinstancechecks when you need to write code that depends on a field's functionality.These attributes can be used together with the Model._meta API to narrow down a search for specific field types.Custom model fields should implement these flags.

Attributes for fields

  • Field.auto_created
  • Boolean flag that indicates if the field was automatically created, suchas the OneToOneField used by model inheritance.

  • Field.concrete

  • Boolean flag that indicates if the field has a database column associatedwith it.

  • Field.hidden

  • Boolean flag that indicates if a field is used to back another non-hiddenfield's functionality (e.g. the content_type and object_id fieldsthat make up a GenericForeignKey). The hidden flag is used todistinguish what constitutes the public subset of fields on the model fromall the fields on the model.

注解

Options.get_fields()excludes hidden fields by default. Pass in include_hidden=True toreturn hidden fields in the results.

  • Field.is_relation
  • Boolean flag that indicates if a field contains references to one ormore other models for its functionality (e.g. ForeignKey,ManyToManyField, OneToOneField, etc.).

  • Field.model

  • Returns the model on which the field is defined. If a field is defined ona superclass of a model, model will refer to the superclass, not theclass of the instance.

Attributes for fields with relations

These attributes are used to query for the cardinality and other details of arelation. These attribute are present on all fields; however, they will onlyhave boolean values (rather than None) if the field is a relation type(Field.is_relation=True).

  • Field.many_to_many
  • Boolean flag that is True if the field has a many-to-many relation;False otherwise. The only field included with Django where this isTrue is ManyToManyField.

  • Field.many_to_one

  • Boolean flag that is True if the field has a many-to-one relation, suchas a ForeignKey; False otherwise.

  • Field.one_to_many

  • Boolean flag that is True if the field has a one-to-many relation, suchas a GenericRelation or the reverse of a ForeignKey; Falseotherwise.

  • Field.one_to_one

  • Boolean flag that is True if the field has a one-to-one relation, suchas a OneToOneField; False otherwise.

  • Field.related_model

  • Points to the model the field relates to. For example, Author inForeignKey(Author, on_delete=models.CASCADE). The related_model fora GenericForeignKey is always None.