显示(在模板中)来自模型的选择 - Django

Display (in Template) choice from Model - Django

我需要从模板调用模型中的选择字段。
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: I gone through choices docs, nothing helped: https://docs.djangoproject.com/en/2.0/ref/models/fields/#choices

您可以在查询中使用 .distinct(),例如:

Model.objects.all().distinct()

参见:https://docs.djangoproject.com/en/2.0/ref/models/querysets/#distinct

我以为你问的是如何在模板中显示值。
因此,如果您想从模型中获得 cat,这应该可以解决 values_list()distinct()

的问题
def cat(request):
    my_model = Model.objects.values_list('field_name').distinct()
    return render(...{'my_model': my_model})

如果你只想在那里选择,你不需要查询数据库,只需在上下文中传递 CAT 个选择。

def cat(request):
    my_model = Model.objects.all()
    return render(...{'post': post, 'cats': Model.CAT})

并且在您的模板中循环遍历 cats

{% for item in cats %}
    {{ item.0 }} {{ item.1 }}
{% endfor %}

@TommyL 说:

views.py:

my_model = Model.objects.values('cat').distinct()

template.html:

{% for i in my_model %} 
    {{ i.cat }} 
{% endfor %}

这个解决方案对我有用

这适用于 me.From 模型传递到模板下拉列表

models.py

Class MyCategory(models.Model):
 CAT_CHOICES=(
    ('1','1'),
    ('2','2'),
    )

  category=models.charField(max_length=2,choices=CAT_CHOICES)

views.py

def view_category(request):
     category_choices=MyCategory.CAT_CHOICES
     template_name='your_template.html'
     context={'category':category_choices}
     return render(request,template_name,context)

模板

<html>
    <head>
        <title>category</title>
    </head>
    <body>

    <select name="category">
       {%for mykey,myvalue in category %}
            <option value="{{mykey}}">{{myvalue}}</option>
        {%endfor%}
     </select>

    </body>

</html>