【问题标题】:Display (in Template) choice from Model - Django从模型中显示(在模板中)选择 - Django
【发布时间】: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


【解决方案1】:

这对我有用。从模型传递到模板下拉列表

模型.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>

【讨论】:

    【解决方案2】:

    @TommyL 说:

    views.py

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

    template.html:

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

    这个解决方案适合我

    【讨论】:

      【解决方案3】:

      如果你只是想在那里选择,你不需要查询数据库,只需在上下文中传递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 %}
      

      【讨论】:

        【解决方案4】:

        我以为您问的是如何在模板中显示值。
        因此,如果您想从您的模型中获取 cat,这应该适用于 values_list()distinct()

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

        【讨论】:

        • 我想调用从模板到模型的选择,很抱歉在我的问题结尾处混淆了句子:(
        • 你能用你尝试过的真实值和预期输出的例子来编辑你的问题
        【解决方案5】:

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

        Model.objects.all().distinct()
        

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

        【讨论】:

        • 在他的例子中:Model.objects.values('cat').distinct()
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-03
        • 2017-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-12-22
        相关资源
        最近更新 更多