如何使 Django 模型中的外键字段可选?
我有以下代码:
subject = models.ForeignKey(subjects)
location = models.ForeignKey(location)
publisher = models.ForeignKey(publisher)
我可能不会拥有书籍的所有三个值。有时我可能不知道主题、地点或出版商。在这种情况下,我想将它们留空。
但如果值存在,那么我需要一个选择框来选择它们。这可能吗?
I have the following code:
subject = models.ForeignKey(subjects)
location = models.ForeignKey(location)
publisher = models.ForeignKey(publisher)
It is possible that I won't have all three values of the books. Sometimes I might not know the subject or location, or publisher. In this case I want to leave them empty.
But if values exist then I need a select box from which to select them. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为了实现这一点,
on_delete
参数与blank=True
和null=True
是必要的,如果你这样做会更好就这样。In order to accomplish this, the
on_delete
argument is necessary along withblank=True
andnull=True
, and it would be better if you do it this way.您需要设置 blank=True 和 null=True 到 models.ForeignKey() 使外键字段可选并且on_delete 也需要设置如下:
*注意,只能设置
blank=True
或null=True
到models.ForeignKey()
不足以使外键字段可选,因此您需要将它们都设置为它。此外,如果您想通过 models.OneToOneField 实现您想要的效果(),您需要设置相同的参数,如下所示:
You need to set blank=True and null=True to models.ForeignKey() to make the foreign key field optional and on_delete also needs to be set to it as shown below:
*Be careful, only setting either
blank=True
ornull=True
tomodels.ForeignKey()
is not enough to make the foreign key field optional so you need to set both of them to it.In addition, if you want to achieve what you want with models.OneToOneField(), you need to set the same arguments as shown below:
当然,只需为您想要保持可选的每个字段添加
blank=True, null=True
即可Sure, just add
blank=True, null=True
for each field that you want to remain optional like