您好,我正在测试Django身份验证和嵌套用户数据。我为用户创建了一个简单的MyProfil
模型。我想测试制作自定义的id
并将primary_key=True
设置为id = models.UUIDField
。
models.py
class MyProfil(models.Model):
id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
aboutme = models.TextField(max_length=300, blank=True)
city = models.TextField(max_length=300, blank=True)
到目前为止,一切都对我有利,但是我有一个问题,即使阅读django文档也无法回答自己。
Question
我的
primary_key=True
字段上的id
是否也表示unique
或我必须声明它?
最佳答案
是。由于主键是指可以唯一标识对象的值。在the documentation on the primary_key
parameter中,我们看到:
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 anAutoField
to hold the primary key, so you don’t need to setprimary_key=True
on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.
primary_key=True
impliesnull=False
andunique=True
. Only one primary key is allowed on an object.
关于Django: "primary_key=True"也指 "unique"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58139212/