Django 从模型访问 CHOICES = ()

Django accessing CHOICES = () from Model

只是想知道,我有以下模型架构:

class Location(models.Model):

    SERVICE_CHOICES = (
        ('bus_station', 'Bus Station'),
        ('cafe', 'Café'),
        ('cinema', 'Cinema'),
        ('gardens', 'Public Gardens'),
        ('library', 'Library'),
        ('public_services', 'Public Services'),
        ('railway_station', 'Railway Station'),
        ('restaurant', 'Restaurant'),
        ('school', 'School'),
        ('shop', 'Shop'),
        ('supermarket', 'Supermarket'),
        ('tourist_attractions', 'Tourist Attractions'),
        ('transit_station', 'Transit Station'),
        ('walks', 'Walks'),
        ('woodland', 'Woodland'),
    )

    title = models.CharField("Title", max_length=60, default='')
    description = models.TextField("Description")
    service_type = models.CharField("Service Type", max_length=80, choices=SERVICE_CHOICES, default='public_service')

我只是想知道如何遍历前端模板上的 SERVICE_CHOICES 元组列表?

{% for service_choice in location.SERVICE_CHOICES %}

?

根据以下建议,我已经在视图中尝试过:

service_types = []

fields = Location._meta.fields()

for field in fields:
    if field.choices:
        service_types.append(field.choices)
Location._meta.get_field('service_type').choices

你可以简单地这样做

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

Location.SERVICE_CHOICES 

在你的 views.py

def view(request):
    ...
    choices = Location._meta.get_field('service_type').choices
    #or 
    choices = Location.SERVICE_CHOICES
    return render(request, 'template.html', { ... 'choices': choices})

您还可以构建一个标签以从模板中获取列表 (Django template tags docs):

templatetags/tags.py

from django import template

register = template.Library()

@register.assignment_tag
def get_choices(instance, field_name):
    return instance._meta.get_field(field_name).choices

template.html

{% get_choices instance 'service_type' as choices %}
{% for item in choices %}
     ...
{% endfor %}