简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM