Django Learning Details:
1.Field options
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 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 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": "to1@example.com"} 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
, winvalid
, 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
.
2.Relationship fields
2.1 Foreignkey
A many-to-one relationship. Requires two positional arguments: the class to which the model is related and the on_delete
option.
1.设置多对一关系外键,需要两个参数:一个是被参照的表,另一个是on_delete选项
To create a recursive relationship – an object that has a many-to-one relationship with itself – use models.ForeignKey('self', on_delete=models.CASCADE)
.
2.为了创建递归关系外键(一个对象和自己又多对一关系),需要设置 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:
3.如果需要创建一个还没有被定义的比对象的外键,可以指明这个对象的名称
from django.db import models class Car(models.Model): manufacturer = models.ForeignKey( 'Manufacturer', on_delete=models.CASCADE, ) # ... class Manufacturer(models.Model): # ... pass
Relationships defined this way on abstract models are resolved when the model is subclassed as a concrete model and are not relative to the abstract model’s app_label
:
4.如果需要创建一个抽象的model,并且自身也对其他表拥有外键,可以在类中使用class meta : abstract = True
from django.db import models class AbstractCar(models.Model): manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE) class Meta: abstract = True
from django.db import models from products.models import AbstractCar class Manufacturer(models.Model): pass class Car(AbstractCar): pass # Car.manufacturer will point to `production.Manufacturer` here.
To refer to models defined in another application, you can explicitly specify a model with the full application label. For example, if the Manufacturer
model above is defined in another application called production
, you’d need to use:
5.1如果你的外键需要参照其他的application,那么可以直接指明需要被参照的对象
class Car(models.Model): manufacturer = models.ForeignKey( 'production.Manufacturer', on_delete=models.CASCADE, )
This sort of reference, called a lazy relationship, can be useful when resolving circular import dependencies between two applications.
5.2这样的参照方式,被称为惰性关系,可以很有效的解决循环导入依赖的问题
A database index is automatically created on the ForeignKey
. You can disable this by setting db_index
to False
. You may want to avoid the overhead of an index if you are creating a foreign key for consistency rather than joins, or if you will be creating an alternative index like a partial or multiple column index.
6.创建依赖的时候默认创建了索引,可以设置db_index为false。这样可以规避索引的开销,因为你也许创建外键只是为了保证数据一致,而不是为了进行表连接,或者因为你想以后自己创建一个部分或者多列的索引。
Behind the scenes, Django appends "_id"
to the field name to create its database column name. In the above example, the database table for the Car
model will have a manufacturer_id
column. (You can change this explicitly by specifying db_column
) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.
7.Django会在后台自动创建_id,(当然你也可一通过明确的指明它的db_cloumn来修改名字),但是我们的永远也无法通过python代码去修改_id,除非直接使用SQL语句
2.2 Arguments
ForeignKey
accepts other arguments that define the details of how the relation works.
2.2.1 ForeignKey.
on_delete
-
When an object referenced by a
ForeignKey
is deleted, Django will emulate 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 referenced object is deleted:user = models.ForeignKey( User, models.SET_NULL, blank=True, null=True, )
on_delete
doesn’t create a SQL constraint in the database. Support for database-level cascade options may be implemented later.
The possible values for on_delete
are found in django.db.models
:
CASCADE
[source]-
Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE 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 all deleted objects.
PROTECT
[source]-
Prevent deletion of the referenced object by raising
ProtectedError
, a subclass ofdjango.db.IntegrityError
.对参照被删除时raise异常
SET_NULL
[source]-
Set the
ForeignKey
null; this is only possible ifnull
isTrue
.
SET_DEFAULT
[source]-
Set the
ForeignKey
to its default value; a default for theForeignKey
must be set.
SET
()[source]-
Set the
ForeignKey
to the value passed toSET()
, or if a callable is passed in, the result of calling it. In most cases, passing a callable will be necessary to avoid executing queries at the time your models.py is imported:from django.conf import settings from django.contrib.auth import get_user_model from django.db import models def get_sentinel_user(): return get_user_model().objects.get_or_create(username='deleted')[0] class MyModel(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET(get_sentinel_user), )
设置自定义值传送给set(),并且以这个值作为外键。如果是可调用对象,那么传入的就是执行后的结果。在大多数案例中,传入的可调用对象必须要注意避免在导入models.py时执行了SQL语句,
DO_NOTHING
[source]-
Take no action. If your database backend enforces referential integrity, this will cause an
IntegrityError
unless you manually add an SQLON DELETE
constraint to the database field.
on_delete=None, # 删除关联表中的数据时,当前表与其关联的field的行为 on_delete=models.CASCADE, # 删除关联数据,与之关联也删除 on_delete=models.DO_NOTHING, # 删除关联数据,什么也不做 on_delete=models.PROTECT, # 删除关联数据,引发错误ProtectedError # models.ForeignKey('关联表', on_delete=models.SET_NULL, blank=True, null=True) on_delete=models.SET_NULL, # 删除关联数据,与之关联的值设置为null(前提FK字段需要设置为可空,一对一同理) # models.ForeignKey('关联表', on_delete=models.SET_DEFAULT, default='默认值') on_delete=models.SET_DEFAULT, # 删除关联数据,与之关联的值设置为默认值(前提FK字段需要设置默认值,一对一同理) on_delete=models.SET, # 删除关联数据, a. 与之关联的值设置为指定值,设置:models.SET(值) b. 与之关联的值设置为可执行对象的返回值,设置:models.SET(可执行对象) ———————————————— 版权声明:本文为CSDN博主「buxianghejiu」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/buxianghejiu/article/details/79086011
2.2.2 ForeignKey.
limit_choices_to
Sets a limit to the available choices for this field when this field is rendered using a ModelForm
or the admin (by default, all objects in the queryset are available to choose). Either a dictionary, a Q
object, or a callable returning a dictionary or Q
object can be used.
For example:
staff_member = models.ForeignKey( User, on_delete=models.CASCADE, limit_choices_to={'is_staff': True}, )
causes the corresponding field on the ModelForm
to list only Users
that have is_staff=True
. This may be helpful in the Django admin.
The callable form can be helpful, for instance, when used in conjunction with the Python datetime
module to limit selections by date range. For example:
def limit_pub_date_choices(): return {'pub_date__lte': datetime.date.utcnow()} 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 choices available in the admin when the field is not listed in raw_id_fields
in the ModelAdmin
for the model.
在前端使用ModelForm进行渲染时,通过limit_choices_to来控制不同用户显示不同数据
2.2.4 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 use for the reverse filter name from the target model). See the related objects documentation for a full explanation and example. Note that you must set this value when defining relations on abstract models; and when you do so some special syntax is available.
If you’d prefer Django not to create a backwards relation, set related_name
to '+'
or end it with '+'
. For example, this will ensure that the User
model won’t have a backwards relation to this model:
user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='+', )
是设指外键在该表的名称,如果设置为“+”或“+”结尾,就不会又反向关系
2.2.5 ForeignKey.
related_query_name
反向查找
The name to use for the reverse filter name from the target model. It defaults to the value of related_name
or default_related_name
if set, otherwise it defaults to the name of the model:
# Declare the ForeignKey with related_query_name class Tag(models.Model): article = models.ForeignKey( Article, on_delete=models.CASCADE, related_name="tags", related_query_name="tag", ) name = models.CharField(max_length=255) # That's now the name of the reverse filter Article.objects.filter(tag__name="important")
Like related_name
, related_query_name
supports app label and class interpolation via some special syntax.
https://blog.csdn.net/weixin_45154837/article/details/99892994
2.2.6.ForeignKey.
to_field
ForeignKey.
to_field
Controls whether or not a constraint should be created in the database for this foreign key. The default is True
, and that’s almost certainly what you want; setting this to False
can be very bad for data integrity. That said, here are some scenarios where you might want to do this:
- You have legacy data that is not valid.
- You’re sharding your database.
If this is set to False
, accessing a related object that doesn’t exist will raise its DoesNotExist
exception.
http://www.mamicode.com/info-detail-2346948.html
对应其他表主键之外的键,但该键必须是唯一的。
2.2.7 ForeignKey.
db_constraint
Controls whether or not a constraint should be created in the database for this foreign key. The default is True
, and that’s almost certainly what you want; setting this to False
can be very bad for data integrity. That said, here are some scenarios where you might want to do this:
- You have legacy data that is not valid.
- You’re sharding your database.
If this is set to False
, accessing a related object that doesn’t exist will raise its DoesNotExist
exception.
设置唯一约束,不设置唯一约束的情况:1.拥有无效的旧数据;2.对数据库正在进行分区;因为唯一约束设置为False,如果参照的实体不存在,就会引出 DoesNotExist
exception.
2.2.8 ForeignKey.
swappable
Controls the migration framework’s reaction if this ForeignKey
is pointing at a swappable model. If it is True
- the default - then if the ForeignKey
is pointing at a model which matches the current value of settings.AUTH_USER_MODEL
(or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.
You only want to override this to be False
if you are sure your model 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 model even if it is swapped out - False
just means that the migrations made with 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’t support, for example).
If in doubt, leave it to its default of True
.
改变关联模型,什么时候改变关联模型?“例如,在某些网站上使用邮件地址而不是用户名作为身份的标识可能更合理。”,重写用户模型
2.3 ManyToManyField
2.3.1
A many-to-many relationship. Requires a positional argument: the class to which the model is related, which works exactly the same as it does for ForeignKey
, including recursive and lazy relationships.
需要设置一个位置参数,一个用来关联的类,它的作用和外键的作用一样,包括递归和lazy关系。
Related objects can be added, removed, or created with the field’s RelatedManager
.
被参照的类可以增加移除或由RelatedManger创建
Database Representation
Behind the scenes, Django creates an intermediary join table to represent the many-to-many relationship. By default, this table name is generated using the name of the many-to-many field and the name of the table for the model that contains it. Since some databases don’t support table names above a certain length, these table names will be automatically truncated and a uniqueness hash will be used, e.g. author_books_9cdf
. You can manually provide the name of the join table using the db_table
option.
在背后,Django其实是创建了一个中间组成,这个中间组成由连接表而诞生,并且代表了多对多关系。并且命名也是两个表名合在一起,如果命名超过了长度限制,也会用hash码来进行代替。如上面的e.g
2.3.2 Arguments
ManyToManyField
accepts an extra set of arguments – all optional – that control how the relationship functions.
2.3.2.1
-
Same as
ForeignKey.related_name
.
-
Same as
ForeignKey.related_query_name
.
ManyToManyField.
limit_choices_to
-
Same as
ForeignKey.limit_choices_to
.limit_choices_to
has no effect when used on aManyToManyField
with a custom intermediate table specified using thethrough
parameter.在多对多关系中,通过参数使用这个选项其实没有作用的。
2.3.2.2
ManyToManyField.
symmetrical
Only used in the definition of ManyToManyFields on self. Consider the following model:
只在自己和自己是多对多的关系中使用
from django.db import models class Person(models.Model): friends = models.ManyToManyField("self")
When Django processes this model, it identifies that it has a
ManyToManyField
on itself, and as a result, it doesn’t add aperson_set
attribute to thePerson
class. Instead, theManyToManyField
is assumed to be symmetrical – that is, if I am your friend, then you are my friend.If you do not want symmetry in many-to-many relationships with
self
, setsymmetrical
toFalse
. This will force Django to add the descriptor for the reverse relationship, allowingManyToManyField
relationships to be non-symmetrical.设置为False可以取消对称关系。
2.3.2.3
ManyToManyField.
through
Django will automatically generate a table to manage many-to-many relationships. However, if you want to manually specify the intermediary table, you can use the
through
option to specify the Django model that represents the intermediate table that you want to use.通过through,指明多对多关系的中间表
The most common use for this option is when you want to associate extra data with a many-to-many relationship.
If you don’t specify an explicit
through
model, there is still an implicitthrough
model class you can use to directly access the table created to hold the association. It has three fields to link the models.如果不用through,仍然存在一个隐式直通模型类,您可以使用它直接访问为保存关联而创建的表。
If the source and target models differ, the following fields are generated:
如果不是同一个model,那么会这么创建:
id
: the primary key of the relation.<containing_model>_id
: theid
of the model that declares theManyToManyField
.<other_model>_id
: theid
of the model that theManyToManyField
points to.
If the
ManyToManyField
points from and to the same model, the following fields are generated:同一个model:
id
: the primary key of the relation.from_<model>_id
: theid
of the instance which points at the model (i.e. the source instance).to_<model>_id
: theid
of the instance to which the relationship points (i.e. the target model instance).
This class can be used to query associated records for a given model instance like a normal model.
2.3.2.4
ManyToManyField.
through_fields
¶-
Only used when a custom intermediary model is specified. Django will normally determine which fields of the intermediary model to use in order to establish a many-to-many relationship automatically. However, consider the following models:
只有在自定义中间表的时候使用,Django选择其中的字段进行多对多关系的自动生成
from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64)
Membership
has two foreign keys toPerson
(person
andinviter
), which makes the relationship ambiguous and Django can’t know which one to use. In this case, you must explicitly specify which foreign keys Django should use usingthrough_fields
, as in the example above.必须在througg_fields里指明要使用的外键,因为Django识别不出来(Membership里,person和inviter都参考了外键Person),所以要指明字段名。
through_fields
accepts a 2-tuple('field1', 'field2')
, wherefield1
is the name of the foreign key to the model theManyToManyField
is defined on (group
in this case), andfield2
the name of the foreign key to the target model (person
in this case).第一个参数是被定义的外键名,第二个参数是目标表的外键名
When you have more than one foreign key on an intermediary model to any (or even both) of the models participating in a many-to-many relationship, you must specify
through_fields
. This also applies to recursive relationships when an intermediary model is used and there are more than two foreign keys to the model, or you want to explicitly specify which two Django should use.如果你在中间表中有个多个外键,那么这些外键的表也参与进多对多关系中,并且都需要用through指明出来。这也适用于存在中间表有两个外键的递归关系中。
Recursive relationships using an intermediary model are always defined as non-symmetrical – that is, with
symmetrical=False
– therefore, there is the concept of a “source” and a “target”. In that case'field1'
will be treated as the “source” of the relationship and'field2'
as the “target”.递归关系中,中间表一般都是设置为非对称的(false),因此存在"souce"和"target"这个概念。field1为sorce,field2为target
2.3.2.5
ManyToManyField.
db_table
-
The name of the table to create for storing the many-to-many data. If this is 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 field itself.
ManyToManyField.
db_constraint
-
Controls whether or not constraints should be created in the database for the foreign keys in the intermediary table. The default is
True
, and that’s almost certainly what you want; setting this toFalse
can be very bad for data integrity. That said, here are some scenarios where you might want to do this:- You have legacy data that is not valid.
- You’re sharding your database.
It is an error to pass both
db_constraint
andthrough
.
ManyToManyField.
swappable
-
Controls the migration framework’s reaction if this
ManyToManyField
is pointing at a swappable model. If it isTrue
- the default - then if theManyToManyField
is pointing at a model which matches the current value ofsettings.AUTH_USER_MODEL
(or another swappable model setting) the relationship will be stored in the migration using a reference to the setting, not to the model directly.You only want to override this to be
False
if you are sure your model should always point towards the swapped-in model - for example, if it is a profile model designed specifically for your custom user model.(可以自定义user model)
If in doubt, leave it to its default of
True
.
ManyToManyField
does not supportvalidators
.多对多关系不支持效验
null
has no effect since there is no way to require a relationship at the database level.2.3
OneToOneField
A one-to-one relationship. Conceptually, this is similar to a
ForeignKey
withunique=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; Multi-table inheritance is implemented by adding an implicit one-to-one relation from the child model to the parent model, for example.
One positional argument is required: the class to which the model will be related. This works exactly the same as it does for
ForeignKey
, including all the options regarding recursive and lazy relationships.https://docs.djangoproject.com/en/2.2/topics/db/examples/one_to_one/