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)
精彩评论