Access Django's field.choices

前端 未结 3 1347
说谎
说谎 2020-12-25 10:17

Is there a way (without using a form) to access a model fields \'choices\' value?

I want to do something like field.choices - and get the list of values either in a

相关标签:
3条回答
  • 2020-12-25 10:20

    Sure, just access the choice attribute of a Model field.

    MyModel._meta.get_field('foo').choices
    my_instance._meta.get_field('foo').choices
    
    0 讨论(0)
  • 2020-12-25 10:23

    If you're declaring your choices like this:

    class Topic(models.Model):
    
        PRIMARY = 1
        PRIMARY_SECONDARY = 2
        TOPIC_LEVEL = ((PRIMARY, 'Primary'),
                      (PRIMARY_SECONDARY, 'Primary & Secondary'),)
    
        topic_level = models.IntegerField('Topic Level', choices=TOPIC_LEVEL,
                default=1)
    

    Which is a good way of doing it really. See: http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/

    Then you can get back the choices simply with Topic.TOPIC_LEVEL

    0 讨论(0)
  • 2020-12-25 10:36

    I think you are looking for get_fieldname_display() function.

    0 讨论(0)
提交回复
热议问题