正如@gareth 中已经暗示的那样answer https://stackoverflow.com/a/9312738,硬编码默认值id
价值可能并不总是最好的主意:
If the id
数据库中不存在该值,您有麻烦了。即使具体的id
值确实存在,对应的对象可能会改变。无论如何,当使用硬编码时id
值,您必须诉诸数据迁移或手动编辑现有数据库内容之类的方法。
为了防止这种情况,你可以使用获取或创建() https://docs.djangoproject.com/en/3.0/ref/models/querysets/#get-or-create结合一个unique
字段(除id
).
这是一种方法:
from django.db import models
class Exam(models.Model):
title = models.CharField(max_length=255, unique=True)
description = models.CharField(max_length=255)
@classmethod
def get_default_pk(cls):
exam, created = cls.objects.get_or_create(
title='default exam',
defaults=dict(description='this is not an exam'),
)
return exam.pk
class Student(models.Model):
exam_taken = models.ForeignKey(
to=Exam, on_delete=models.CASCADE, default=Exam.get_default_pk
)
Here an Exam.title
字段用于获取唯一的对象,以及Exam.description
字段说明了我们如何使用defaults
论证(对于get_or_create
) 完全指定默认值Exam
object.
请注意,我们返回一个pk
,正如建议的docs https://docs.djangoproject.com/en/3.0/ref/models/fields/#default:
对于像这样的领域ForeignKey
映射到模型实例,默认值应该是它们引用的字段的值(pk
unless to_field
已设置)而不是模型实例。
另请注意default
可调用对象的评估在Model.__init__()
(source https://github.com/django/django/blob/stable/3.0.x/django/db/models/base.py#L474)。因此,如果您的默认值取决于同一模型的另一个字段,或者请求上下文,或者客户端表单的状态,您可能应该看看别处 https://stackoverflow.com/a/1969081.