makozaki
makozaki

Reputation: 4366

List all nullable django model fields

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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

Related Questions