Can I make the foreign key field optional in Django model

DjangoDjango Models

Django Problem Overview


I have this code

subject      = models.ForeignKey(subjects)
location     = models.ForeignKey(location)
publisher    =  models.ForeignKey(publisher)

There its not always possible that I have three values of books. so sometimes if I don't know subject or location, or publisher. Then I want to keep them empty

But if I have then I need select box to select. is it possible like that

Django Solutions


Solution 1 - Django

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)

Solution 2 - Django

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)

Solution 3 - Django

null=True


subject=models.ForeignKey(subjects, on_delete=models.CASCADE, default=None, blank=True, null=True)

Field.null

If True, Django will store empty values as NULL in the database. Default is False.

Avoid using null on string-based fields such as CharField and TextField. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string. In most cases, it’s redundant to have two possible values for “no data;” the Django convention is to use the empty string, not NULL. One exception is when a CharField has both unique=True and blank=True set. In this situation, null=True is required to avoid unique constraint violations when saving multiple objects with blank values.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1View Question on Stackoverflow
Solution 1 - DjangoAbid AView Answer on Stackoverflow
Solution 2 - DjangoMuhammad ZubairView Answer on Stackoverflow
Solution 3 - DjangoMD SHAYONView Answer on Stackoverflow