简体   繁体   中英

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?

This is my HTML in case it would be needed:

 {% 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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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