【问题标题】:How to get all objects of a choice field?如何获取选择字段的所有对象?
【发布时间】:2023-01-13 13:26:49
【问题描述】:

我正在做一个搜索表单,用户在其中选择类别和产品类型,这是产品模型的选择字段,product_type = models.CharField(max_length=30, choices=TYPE, default='Physical')。我可以获取类别,但不能获取要添加到表单的 TYPE 中的选项。

选择.py

TYPE = [
    ('PHYSICAL', _('Physical')),
    ('DIGITAL', _('Digital')),
]

视图.py

from .choices import TYPE

def is_valid_queryparam(param):
    return param != '' and param is not None

def FilterView(request):
    qs = Product.objects.all()
    categories = Category.objects.all()
    ptypes = Product.product_type.all()  # The problem line

    category = request.GET.get('category')
    ptype = request.GET.get('ptype')

    if is_valid_queryparam(category) and category != 'Choose...':
        qs = qs.filter(category__name=category)

    if is_valid_queryparam(ptype) and ptype != 'Choose...':
        qs = qs.filter(product_type=ptype)

    context = {
        'queryset': qs,
        'categories' : categories,
        'ptypes' : ptypes,
    }

    return render(request, 'categories/display_query.html', context)

基础.html

    <div>
    <h3>Advanced Search</h3>
        <form method="GET" action="{% url 'filter-view' %}">
            <div>
                <label for="category">Category</label>
                <select name="category">
                    <option selected>Choose...</option>
                    {% for cat in categories %}
                    <option value="{{ cat }}">{{ cat }}</option>
                    {% endfor %}
                </select>
            </div>
            <div>
                <label for="ptype">Product type</label>
                <select name="ptype">
                    <option selected>Choose...</option>
                    {% for type in ptype %}
                    <option value="{{ type }}">{{ type }}</option>
                    {% endfor %}
                </select>
            </div>
            <button type="submit">Search</button>
        </form>
    </div>

显示查询.html

{% extends 'products/base.html' %}
{% block content %}
<div>
    <ul>
        {% for product in queryset %}
            <li>
                {{ product.title }}
                <span>Author: {{ product.author.username }}</span>
            </li>
        {% endfor %}
     </ul>
</div>
{% endblock content %}

【问题讨论】:

    标签: python django django-forms


    【解决方案1】:

    您可以使用给定的代码:

    p_types_keys = [i[0] for i in TYPE]
    p_types_values = [i[1] for i in TYPE]
    ptype_dict = dict(zip(p_types_keys, p_types_values))
    

    该行将返回您的“TYPE”的所有键 第二行将返回你的“TYPE”的所有键 第三行将返回您的类型的键值对以添加表单。

    【讨论】:

      猜你喜欢
      • 2020-04-11
      • 1970-01-01
      • 2022-11-23
      • 2022-12-01
      • 1970-01-01
      • 2021-10-21
      • 2016-03-29
      • 2018-07-20
      • 1970-01-01
      相关资源
      最近更新 更多