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

标签 python django

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

用户将使用 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

关于python - 计算模型语法中 City 对象的实例数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55326302/

相关文章:

python - Pandas 没有安装在 virtualenv 中,尽管看起来是这样

python - Django Formset - 检查行标记是否已删除

django - 如何将 IntelliJ 实时编辑与 django 模板结合使用?

python - Django 1.8 管理表单 : AttributeError XForm object has no attribute 'save_m2m'

python - 如何使用 django 1.7.3/postgres 迁移在数据库中设置默认列值?

python - 在 Python 3.4 中使用 input() 时出现 NameError

python - 当输入为不同类型时,Numpy matmul 需要的内存比所需的内存多

python - 寻找 Python 代码作为 MODBUS 从机

python - Jupyter notebook 命令在 Mac 上不起作用

django - 如何在 django : Storage or database 中存储 google oauth token