Skip to main content
 首页 » 编程设计

python之计算模型语法中 City 对象的实例数

2024年11月24日7开发

我将简要说明我正在尝试做什么。

用户将使用 email 进行注册, first and last name , 然后选择 city (由名为 Waitlist 的模型处理)。

我正在使用 django_cities_light用于城市选择。

我想定义一个 queryset计算特定城市被选中的次数,然后将该数字输出到我的 template_name 上页面。

例)3 位用户注册,2 人选择 London作为他们的城市,因此有 2 个 London 的实例我的城市对象 Waitlist模型。我希望能够针对多个城市轻松执行此操作。

然后我想渲染这个 2使用{{ for London in waitlist.qs }}例如(我不确定语法,因此我问的原因)。

我将展示我到目前为止所做的事情,如果有人能向我解释如何正确定义查询集,我将不胜感激!

View .py

class HomeView(TemplateView): 
    template_name = 'home/home.html' 
    def get(self, request, *args, **kwargs): 
        london = Waitlist.objects.get(??) 
        context = { 
            'london': london, 
        } 
        return render(request, self.template_name, context) 

模型.py

class Waitlist(models.Model): 
    first_name            = models.CharField(max_length=30, null=True) 
    last_name = models.CharField(max_length=30, null=True) 
    email = models.CharField(max_length=40, null=True) 
    city            = models.ForeignKey(City, null=True, blank=True, on_delete=models.CASCADE) 

请您参考如下方法:

可能您需要这样的东西,获取所有城市并准备数据:

class HomeView(TemplateView): 
    template_name = 'home/home.html' 
 
    def get(self, request, *args, **kwargs): 
        query = Waitlist.objects.all() 
        data = {} 
        for cname in query.values('city__name').distinct(): 
            city = cname['city__name'] 
            data[city] = query.filter(city__name=city) 
        context = { 
            'data': data, 
        } 
        return render(request, self.template_name, context) 

在模板中

{% for city, details in data.items %} 
    <strong>{{ city }}, total - {{ details|length }}:<strong> 
    <ul> 
    {% for wait_item in details %} 
        <li>{{ wait_item.first_name }} - {{ wait_item.email }}</li> 
    {% endfor %} 
    </ul> 
<hr> 
{% endfor %} 

如果您只需要伦敦 在 View 中它应该是:

class HomeView(TemplateView): 
    template_name = 'home/home.html' 
 
    def get(self, request, *args, **kwargs): 
        data = Waitlist.objects.filter(city__name__iexact='london') 
         context = { 
            'data': data, 
        } 
        return render(request, self.template_name, context) 

在模板中:

    <strong>London, total - {{ data|length }}:<strong> 
    <ul> 
    {% for wait_item in data %} 
        <li>{{ wait_item.first_name }} - {{ wait_item.email }}</li> 
    {% endfor %} 
    </ul> 

您可以阅读查询的详细信息 iexact , distinct