How to get all fields with choices in a Django model?

I have a Django model with dozen fields with Choice options and I want to serialize their values to write an CSV file.

How can I traverse the fields to find the ones with Choices options? Something like that:

for field in MyModel._meta.fields:
    if field.has_choices_on_it():
        print(f.name)

Each field has a .choices that is by default None, so we can check if it is None. Note however that .choices doesn't have to be a sequence of values, it can also be a function that produces values when needed (for example because it makes database requests, consumes an API, etc.).

for field in MyModel._meta.fields:
    if field.choices is not None:
        print(f.name)
        choices = field.choices
        if callable(choices):
            choices = choices()
        print(choices)
Back to Top