How to make the foreign key field optional in Django model? Ask Question

How to make the foreign key field optional in Django model? Ask Question

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?

ベストアンサー1

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)

おすすめ記事