[Django]-How to make the foreign key field optional in Django model?

275👍

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)
👤Abid A

10👍

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👍

You need to set blank=True and null=True to models.ForeignKey() to make the foreign key field optional and on_delete also needs to be set to it as shown below:

my_field = models.ForeignKey(
    Parent_model, 
    blank=True, # Here
    null=True, # Here
    on_delete=models.CASCADE # Here
)

*Be careful, only setting either blank=True or null=True to models.ForeignKey() is not enough to make the foreign key field optional so you need to set both of them to it.

In addition, if you want to achieve what you want with models.OneToOneField(), you need to set the same arguments as shown below:

my_field = models.OneToOneField(
    Parent_model, 
    blank=True, # Here
    null=True, # Here
    on_delete=models.CASCADE # Here
)

Leave a comment