Can I make the foreign key field optional in Django model

Viewed 76069

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?

2 Answers

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