Reputation: 4366
I have a model with both nullable and non-nullable fields. Let's consider an example:
from django.db import models
class MyModel(models.Model):
field_1 = models.CharField(null=False)
field_2 = models.CharField(null=True)
field_3 = models.ForeignKey(SomeOtherModel, null=True)
field_4 = models.ForeignKey(YetAntherModel, null=False)
How could I get list of nullable field names (as in example below) from MyModel class?
['field_2', 'field_3']
Right now I have hardcoded mapping which I need to update together with model changes so I'd like to have some generic method for it.
Any idea would be appricieated.
Upvotes: 3
Views: 306
Reputation: 477240
You can iterate over the fields, and filter the null
paramete, like:
[f for f in MyModel._meta.get_fields() if f.null]
Or if you are only interested in the field name (not the field), then you can write:
[f.name for f in MyModel._meta.get_fields() if f.null]
For your given MyModel
, this gives us the expected:
>>> [f.name for f in MyModel._meta.get_fields() if f.null]
['field_2', 'field_3']
Upvotes: 3