Django Learning Details:
1.Field
1.1 null(Field.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 adn TextField.If a string0based field has "null=True", that means it has two possible values for "no data":and the empty string. In most cases, it’s redundant to(多余) have two possible values for “no data;” ,the Django conevntion 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 stoage(see blank).
在基于字符的Field类里(例如CharField 和 TextField),应该避免使用null。因为对于它们来说空值代表两个意思:空字符串和值为null。blabla一堆,意思就是字符串Field里不要使用null就行了,用了会报错。
1.2 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.
空值null是和数据库相关的,而空值blank是和验证相关的,只要设置了"blank = True"那么输入的时候, 就会验证并允许输入的值是为空的。如果为False,那么该字段是必须输入的字段。
1.3 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 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.
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:
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 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 sequence 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
.
1.choice它由两个可迭代的对象构成(list,tuple),在网页上的表现形式是下拉框(select box)
2.命名标准:第一个参数是model里面实际的值,第二个参数是给用户阅读的值
3.choice列表最好放在当前的类里,但并不是强制的,放在同一个类里可以将choice列表的信息都保存在使用它的类中,同时还可以让choice更容易参照
4.choice还可以让第二个参数也是一个二元tuple
5.设定好的choice,可以使用Model.
get_FOO_display
()来查看数值
6.如果你发现自己的choice每一次生成的顺序都不一样,最好根据数据库的外键ForeignKey
. choices来做选择,因为这样插入的数据都是静态的。
7.如果设置了"blank = False",且是默认设置,那么下拉列表默认显示“------------”。可以对默认显示进行修改,"(None, 'Your String For Display')"
1.4 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_column是在数据库中的字段名称,默认和变量同名;但是万一你的db_column是数据库的保留字段,或者包含了一些不能在python变量里出现的字符,django会在后台为我们加上列名和表名
1.5 db_index(Field.db_index)
If True
, a database index will be created for this field.
默认为False,设置为True,则可以创建索引
1.6 db_tablespace(Field.db_tablespace)
The name of the database tablespace to use for this field’s index, if this field is indexed. The default is the project’s DEFAULT_INDEX_TABLESPACE
setting, if set, or the db_tablespace
of the model, if any. If the backend doesn’t support tablespaces for indexes, this option is ignored.
1.7defalut(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": "[email protected]"} contact_info = JSONField("ContactInfo", default=contact_default)
lambda
s 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
.
1.给字段设置的默认值,他可以是一个确定的value也可能是一个可回调对象,如果是可回调对象,那么每一次产生新对象的时候都会产生一次新的回调结果。
2.默认值不能设置为变长对象(例如model instance,列表,集合等等)
3.作为对该对象同一实例的引用,它将在所有新模型实例中用作默认值。
4.我们可以通过选择一个具体dict或者JsonField替换掉默认值
5.lambda函数不能作为默认值,因为它在移植的过程中,不能被序列化
6.对于外键字段,外键字段默认值应该对于它们所参照的值,而不应该是一个model实例
7.默认值在一个model实例化时并且没有值提供给它时使用,如果是主键的情况并且没有值的情况下下也会使用默认值
1.8 editable(Field.editable)
If False
, the field will not be displayed in the admin or any other ModelForm
. They are also skipped during model validation. Default is True
.
1.9 error_messages(Field.error_messages)
The
error_messages
argument lets you override the default messages that the field will raise. Pass in a dictionary with keys matching the error messages you want to override.
Error message keys include null
, blank
, invalid
, invalid_choice
, unique
, and unique_for_date
. Additional error message keys are specified for each field in the Field types section below.
These error messages often don’t propagate to forms. See Considerations regarding model’s error_messages.
1.可以重写错误信息,并且以字典的形式传递出去
2.错误关键字包括null
, blank
, invalid
, invalid_choice
, unique
, unique_for_date
.