只是想知道,我有以下模型架构:
dbRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
User user = new User();
String currentUserId = mAuth.getCurrentUser().getUid();
user.setLatitude(String.valueOf(userLocation.latitude));
user.setLongitude(String.valueOf(userLocation.longitude));
dbRef.child("users").child(currentUserId).setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.i("Info", "updateUser:success");
} else {
Log.i("Info", "updateUser:failure");
}
}
});
我只是想知道如何循环前端模板上的SERVICE_CHOICES元组列表?
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')
根据以下建议,我在视图中尝试了这个:
{% for service_choice in location.SERVICE_CHOICES %}
答案 0 :(得分:1)
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 %}
答案 1 :(得分:0)
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