我有以下型号
models.py
class Category(models.Model):
label = models.CharField(max_length=100, unique=True)
description = models.CharField(max_length=255, blank=True)
class Expense(models.Model):
description = models.CharField(max_length=255, blank=True)
amount = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)
category = models.ForeignKey(
Category,
on_delete=models.CASCADE,
null=True,
related_name='category'
)
class CategoryViewSet(viewsets.ModelViewSet):
queryset = Category.objects.order_by("-expense__expense")
我正在努力返回如何按Expense模型中最挑剔的类别排序的类别列表,例如:
<Expense category=3>
<Expense category=3>
<Expense category=2>
<Expense category=3>
<Expense category=1>
<Expense category=1>
我要按此顺序退货:
<Category id=3>
<Category id=1>
<Category id=2>
queryset = Category.objects.annotate(
expense_count=Count('category')).order_by('-expense_count')
答案 0 :(得分:0)
使用Django可爱的aggregation features。
async componentDidMount () {
const res = await fetch(smth);
this.setState({data: res}, async () => {
// put the second fetch here
const res2 = await fetch(another);
this.setState({data2: res2});
});
}
答案 1 :(得分:0)
我们可以使用annotate来实现:
from django.db.models import Count
...
queryset = Category.objects.annotate(expense_count=Count('expense')).order_by('-expense_count')
答案 2 :(得分:0)
from django.db.models import Count
Category.objects.annotate(expense_count=Count('category')).order_by('-expense_count')
这是基于您的模型定义的,但是我建议将related_name
修改为与Expense
相关的术语,例如expenses
。由于related_name
表示您用于反向查询的名称。
答案 3 :(得分:0)
只需在查询末尾添加.distinct('field-name')。像这样
queryset = Category.objects.order_by("-expense__expense").distinct('category')