如何通过关系外键在Django模型中排序查询集

时间:2020-01-24 10:12:11

标签: django rest model foreign-keys

我有以下型号

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')

4 个答案:

答案 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')