简体   繁体   English

如何在 Django 中正确进行查询?

[英]How to properly make a query in Django?

I've ran into a little problem.我遇到了一个小问题。 I want to construct a proper queryset to get values which represent the number of the expenses per category to display this like that.我想构建一个适当的查询集来获取表示每个类别的费用数量的值,以这样显示

This is what I got now:这是我现在得到的:

class CategoryListView(ListView):
    model = Category
    paginate_by = 5

    def get_context_data(self, *, category_object_list=None, **kwargs):
        **categories = Category.objects.annotate(Count('expense'))
        queryset = categories.values('expense__count')**


    return super().get_context_data(
        category_object_list=queryset,
        **kwargs)

Of course it doesnt work and I have terrible table like this.当然它不起作用,我有这样糟糕的桌子 I suppose the problem isn't in HTML but in my absolutely wrong query... What should I do?我想问题不在 HTML 中,而是在我完全错误的查询中......我该怎么办?

This is my HTML in case it would be needed:这是我的 HTML,以防需要它:

 {% for category in object_list %}
    <tr>
    <td>
        {{ category.name|default:"-" }}
    </td>
        <td>
            {% for number in category_object_list %}
                {{ number.expense__count }}
            {% endfor %}
        </td>
    <td>
      <a href="{% url 'expenses:category-update' category.id %}">edit</a>
      <a href="{% url 'expenses:category-delete' category.id %}">delete</a>
    </td>
{% endfor %}
    </tr>

Also my models.py:还有我的models.py:

class Category(models.Model):
name = models.CharField(max_length=50, unique=True)

def __str__(self):
    return f'{self.name}'


class Expense(models.Model):
    class Meta:
        ordering = ('-date', '-pk')

    category = models.ForeignKey(Category, null=True, blank=True, 
    on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    amount = models.DecimalField(max_digits=8, decimal_places=2)
    date = models.DateField(default=datetime.date.today, db_index=True)

    def __str__(self):
        return f'{self.date} {self.name} {self.amount}'

You can try like this within your template with the reverse look up of Foregin Keys.您可以通过反向查找外键在模板中尝试这样做。 See the docs for more detail.有关更多详细信息,请参阅文档

{% for category in object_list %}
    <tr>
    <td>
        {{ category.name|default:"-" }}
    </td>
        <td>
            {{category.expense_set.all.count}}
        </td>
    <td>
      <a href="{% url 'expenses:category-update' category.id %}">edit</a>
      <a href="{% url 'expenses:category-delete' category.id %}">delete</a>
    </td>
{% endfor %}
    </tr>

Now in the view you can just pass all the categories with the ListView现在在视图中,您可以使用ListView传递所有类别

class CategoryListView(ListView):
    model = Category
    paginate_by = 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM