Vingtoft
Vingtoft

Reputation: 14606

Django: Print out all choices for a models.Model class

Im trying to write an algorithm that prints out all choices in a Django model class.

For example: I have a model:

class SomeModel(models.Model):
  field_a = models.SmallIntegerField(choices=[(1, "a"), (2, "b"), (3, "c")]
  field_b = models.CharField(max_length=255)

The expected output is something like this:

"field_a": [(1, "a"), (2, "b"), (3, "c")]

Please note the algorithm should ignore field_b because of the missing choices attribute.

Any idea on how this functionality can be achieved?

Upvotes: 0

Views: 384

Answers (1)

NS0
NS0

Reputation: 6096

Have a look at the meta options documentation. You can achieve this in the following way:

fields = SomeModel._meta.fields()
for field in fields:
    if field.choices:
        print "%s: %s" % (field.name, field.choices)

Upvotes: 1

Related Questions