【发布时间】:2018-10-19 02:29:48
【问题描述】:
我需要从模板调用模型中的选择字段。
models.py:
...
CAT = (
("1", "1"),
("2", "2"),
)
cat = models.CharField(max_length=2, choices=TYPE, default="")
...
views.py:
def cat(request):
my_model = Model.objects.all()
return render(...{'post': post})
template.html:
{% for i in my_model%}
{{ i.cat }}
# This shows DUPLICATES if I have couple posts with same cat.
# I want to display uniques in choices (I am not interested in posts at all)
{% endfor %}
那么我怎样才能从模板中调用模型中的选项而不显示重复项?
P.S:我浏览了选择文档,没有任何帮助:https://docs.djangoproject.com/en/2.0/ref/models/fields/#choices
【问题讨论】:
-
在视图中:my_model = Model.objects.values('cat').distinct() 和模板 {% for i in my_model %} {{ i.cat }} {% endfor %}
标签: django django-models django-templates django-template-filters