如何使 Django 模型中的外键字段可选?

发布于 2024-11-18 22:24:46 字数 287 浏览 1 评论 0原文

我有以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

度的依靠╰つ 2024-11-25 22:24:47

为了实现这一点,on_delete 参数与 blank=Truenull=True 是必要的,如果你这样做会更好就这样。

subject = models.ForeignKey(subjects, on_delete=models.SET_NULL, blank=True, null=True)

In order to accomplish this, the on_delete argument is necessary along with blank=True and null=True, and it would be better if you do it this way.

subject = models.ForeignKey(subjects, on_delete=models.SET_NULL, blank=True, null=True)
三生殊途 2024-11-25 22:24:47

您需要设置 blank=Truenull=Truemodels.ForeignKey() 使外键字段可选并且on_delete 也需要设置如下:

my_field = models.ForeignKey(
    Parent_model, 
    blank=True, # Here
    null=True, # Here
    on_delete=models.CASCADE # Here
)

*注意,只能设置 blank=Truenull=Truemodels.ForeignKey() 不足以使外键字段可选,因此您需要将它们都设置为它。

此外,如果您想通过 models.OneToOneField 实现您想要的效果(),您需要设置相同的参数,如下所示:

my_field = models.OneToOneField(
    Parent_model, 
    blank=True, # Here
    null=True, # Here
    on_delete=models.CASCADE # Here
)

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:

my_field = models.ForeignKey(
    Parent_model, 
    blank=True, # Here
    null=True, # Here
    on_delete=models.CASCADE # Here
)

*Be careful, only setting either blank=True or null=True to models.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:

my_field = models.OneToOneField(
    Parent_model, 
    blank=True, # Here
    null=True, # Here
    on_delete=models.CASCADE # Here
)
度的依靠╰つ 2024-11-25 22:24:46

当然,只需为您想要保持可选的每个字段添加 blank=True, null=True 即可

subject = models.ForeignKey(subjects, blank=True, null=True)

Sure, just add blank=True, null=True for each field that you want to remain optional like

subject = models.ForeignKey(subjects, blank=True, null=True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文