首页 > 解决方案 > Python / Django - 编辑渲染输出

问题描述

我是 python 新手,我有以下问题。我有一个对应数据库,其中包含两个布尔字段,即“is_client”和“is_supplier”。当添加对应方时,可以是客户或供应商,或两者兼而有之。

我想显示 if is_client=True c_type = "client", if is_supplier=True c_type = "supplier" 并且如果两者都是 True c_type = "client / supplier"

如何在以下功能中做到这一点?

class CounterpartsListView(ListView):
model = Counterpart
template_name = "counterparts/view_list.html" 
context_object_name = "counterparts"

def get_queryset(self):
    c_type = self.kwargs.get("type")
    if c_type == "suppliers":
        if Counterpart.objects.filter(is_supplier=True).count() >= 1:
            return (
                Counterpart.objects.filter(is_supplier=True)
                .order_by("counterpart_name")
                .extra(select={"Supplier": "is_supplier"})
            )
        else:
            return Counterpart.objects.all().order_by("counterpart_name")
    elif c_type == "customers":
        if Counterpart.objects.filter(is_client=True).count() >= 1:
            return (
                Counterpart.objects.filter(is_client=True)
                .order_by("counterpart_name")
                .extra(select={"Customer": "is_client"})
            )
        else:
            return Counterpart.objects.all().order_by("counterpart_name")
    else:
        return Counterpart.objects.all().order_by("counterpart_name")

这是 html 输出,如何添加 c_type 属性?

{% for counterpart in counterparts %}
     <tr>
        <td>{{ counterpart.counterpart_name }}</td>
        <td>{{ counterpart.city }}</td>
        <td>{{ counterpart.country }}</td>
        <td>{{ counterpart.c_type }}</td>
      </tr>
{% endfor %}

或者,我正在考虑更改输入法,而不是两个单独的字段(is_client 和 is_supplier),只有一个名为 c_type 并添加一个值(客户或供应商),以防两者都添加一个数组。或者有什么更好的解决方案?

谢谢您的帮助

标签: pythonsqldjango

解决方案


我想通了..至少这是一个适用于我的情况的解决方案..很明显,我看不到它:) view_all.html

{% if counterpart.is_supplier %} Supplier {% endif %}
{% if counterpart.is_supplier and counterpart.is_client %} / {% endif %}
{% if counterpart.is_client %} Customer {% endif %}

我仍然有兴趣学习其他可以更好地处理它的方法谢谢


推荐阅读