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)
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)
- [Django]-How does Django's nested Meta class work?
- [Django]-Does django with mongodb make migrations a thing of the past?
- [Django]-How to automate createsuperuser on django?
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
)
- [Django]-Django Rest Framework Conditional Field on Serializer
- [Django]-Mixin common fields between serializers in Django Rest Framework
- [Django]-Django-DB-Migrations: cannot ALTER TABLE because it has pending trigger events
Source:stackexchange.com