null
If True, Django will store empty values as NULL in the database. Default is False.
Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.
For both string-based and non-string-based fields, you will also need to set blank=True if you wish to permit empty values in forms, as the null parameter only affects database storage (see blank).
related_name
class Map(db.Model):
members = models.ManyToManyField(User, related_name='maps',
verbose_name=_('members'))
# current_user.maps.all()
The related_name attribute specifies the name of the reverse relation from the User model back to your model.
If you don’t specify a related_name, Django automatically creates one using the name of your model with the suffix _set, for instance User.map_set.all().
If you do specify, e.g. related_name=maps on the User model, User.map_set will still work, but the User.maps. syntax is obviously a bit cleaner and less clunky; so for example, if you had a user object current_user, you could use current_user.maps.all() to get all instances of your Map model that have a relation to current_user.
blank
Field.blank
If True, the field is allowed to be blank. Default is False.
Note that this is different than null. null is purely database-related, whereas blank is validation-related. If a 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¶
An iterable (e.g., a list or tuple) consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for this field. If choices are given, they’re enforced by model validation and the default form widget will be a select box with these choices instead of the standard 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:
YEAR_IN_SCHOOL_CHOICES = (
(‘FR’, ‘Freshman’),
(‘SO’, ‘Sophomore’),
(‘JR’, ‘Junior’),
(‘SR’, ‘Senior’),
)
Generally, it’s best to define choices inside a model class, and to define a suitably-named constant for each value:
from django.db import models
class Student(models.Model):
FRESHMAN = ‘FR’
SOPHOMORE = ‘SO’
JUNIOR = ‘JR’
SENIOR = ‘SR’
YEAR_IN_SCHOOL_CHOICES = (
(FRESHMAN, ‘Freshman’),
(SOPHOMORE, ‘Sophomore’),
(JUNIOR, ‘Junior’),
(SENIOR, ‘Senior’),
)
year_in_school = models.CharField(
max_length=2,
choices=YEAR_IN_SCHOOL_CHOICES,
default=FRESHMAN,
)
def is_upperclass(self):
return self.year_in_school in (self.JUNIOR, self.SENIOR)
Though you can define a choices list outside of a model class and then refer to it, defining the choices and names for each choice inside the model class keeps all of that information with the class that uses it, and makes the choices easy to reference (e.g, Student.SOPHOMORE will work anywhere that the Student model has been imported).
You can also collect your available choices into named groups that can be used for organizational purposes:
MEDIA_CHOICES = (
('Audio', (
('vinyl', 'Vinyl'),
('cd', 'CD'),
)
),
('Video', (
('vhs', 'VHS Tape'),
('dvd', 'DVD'),
)
),
('unknown', 'Unknown'),
)
The first element in each tuple is the name to apply to the group. The second element is an iterable of 2-tuples, with each 2-tuple containing a value and a human-readable name for an option. Grouped options may be combined with ungrouped options within a single list (such as the unknown option in this example).
For each model field that has choices set, Django will add a method to retrieve the human-readable name for the field’s current value. See get_FOO_display() in the database API documentation.
Note that choices can be any iterable object – not necessarily a list or tuple. This lets you construct choices dynamically. But if you find yourself hacking choices to be dynamic, you’re probably better off using a proper database table with a ForeignKey. choices is meant for static data that doesn’t change much, if ever.
Unless blank=False is set on the field along with a default then a label containing “---------” will be rendered with the select box. To override this behavior, add a tuple to choices containing None; e.g. (None, ‘Your String For Display’). Alternatively, you can use an empty string instead of None where this makes sense - 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 contains characters that aren’t allowed in Python variable names – notably, the hyphen – that’s OK. Django quotes column and table names behind the scenes.
db_index¶
Field.db_index¶
If True, a database index will be created for this field.
default¶
Field.default¶
The default value for the field. This can be a value or a callable object. If callable it will be called every time a new object is created.
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 default value in all new model instances. Instead, wrap the desired default in a callable. For example, if you want to specify a default dict for JSONField, use a function:
def contact_default():
return {"email": "to1@example.com"}
contact_info = JSONField(“ContactInfo”, default=contact_default)
lambdas can’t be used for field options like default because they can’t be serialized by migrations. See that documentation for other caveats.
For fields like ForeignKey that map to model instances, defaults should be the value of the field they reference (pk unless to_field is set) instead of model instances.
The default value is used when new model instances are created and a value isn’t provided for the field. When the field is a primary key, the default is also used when the field is set to None.
help_text¶
Field.help_text¶
Extra “help” text to be displayed with the form widget. It’s useful for documentation even if your field isn’t used on a form.
Note that this value is not HTML-escaped in automatically-generated forms. This lets you include HTML in help_text if you so desire. For example:
help_text=“Please use the following format: YYYY-MM-DD.”
Alternatively you can use plain text and django.utils.html.escape() to escape any HTML special characters. Ensure that you escape any help text that may come from untrusted users to avoid a cross-site scripting attack.
primary_key¶
Field.primary_key¶
If True, this field is the primary key for the model.
If you don’t specify primary_key=True for any field in your model, Django will automatically add an AutoField to hold the primary key, so you don’t need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see 自动设置主键.
primary_key=True implies null=False and unique=True. Only one primary key is allowed on an object.
The primary key field is read-only. If you change the value of the primary key on an existing object and then save it, a new object will be created alongside the old one.
unique¶
Field.unique¶
If True, this field must be unique throughout the table.
This is enforced at the database level and by model validation. If you try to save a model with a duplicate value in a unique field, a django.db.IntegrityError will be raised by the model’s save() method.
This option is valid on all field types except ManyToManyField and OneToOneField.
Note that when unique is True, you don’t need to specify db_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 to require that this field be unique for the value of the date field.
For example, if you have a field title that has unique_for_date=“pub_date”, then Django wouldn’t allow the entry of two records with the same title and pub_date.
Note that if you set this to point to a DateTimeField, only the date portion of the field will be considered. Besides, when USE_TZ is True, 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 validation but not at the database level. If any unique_for_date constraint involves fields that are not part of a ModelForm (for example, if one of the fields is listed in exclude or has editable=False), Model.validate_unique() will skip validation for that particular constraint.
unique_for_month¶
Field.unique_for_month¶
Like unique_for_date, but requires the field to be unique with respect to the month.
unique_for_year¶
Field.unique_for_year¶
Like unique_for_date and unique_for_month.
verbose_name¶
Field.verbose_name¶
A human-readable name for the field. If the verbose name isn’t given, Django will automatically create it using the field’s attribute name, converting underscores to spaces. See Verbose field names.
validators¶
Field.validators¶
A list of validators to run for this field. See the validators documentation for more information.
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, and how lookups are fetched from a field.