0

我有几个用户,这些用户有几个客户。每个客户都有一个国家属性。我想在我的项目中列出客户所在的国家/地区。我用 for 循环尝试过,但是当多个客户拥有相同的国家/地区时,它会多次列出相同的国家/地区。我想一次性列出所有国家。我怎样才能做到这一点?

这是我的代码

视图.py

def country_customer_list(request):
    current_user = request.user
    userP = UserProfile.objects.get_or_create(username=current_user)
    customer_list = Customer.objects.filter(company=userP[0].company.comp_name)


    context = {
        'customer_list': customer_list,
    }
    
    return render(request, 'country_customer_list.html', context)

模型.py

class Customer(models.Model):

    customer_name = models.CharField(max_length=20)
    country = models.CharField(max_length=20)
    ..
    email = models.CharField(max_length=30)

country_customer_list.html

                                <table id="multi-filter-select" class="display table table-striped table-hover grid_" >
                                    <thead>
                                        <tr>
                                            <th>Country</th>
                                            <th>Operations</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    {% for customer in customer_list %}
                                        <tr>
                                            <td>{{customer.country}}</td>

                                            <td>
                                                ...
                                            </td>
                                        </tr>
                                    {% endfor %}
                                    </tbody>
</table>
4

1 回答 1

1

如果您只是想要该country字段中所有不同值的列表,您可以使用distinct()

countries = Customer.objects.values_list('country', flat=True).distinct()

values_list(flat=True)结果转换为仅包含查询感兴趣的一个值的平面列表。

于 2021-03-05T08:47:10.650 回答