开发者

Can I make the foreign key field optional in Django model

I have the fo开发者_StackOverflow中文版llowing 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?


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)


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜