【问题标题】:How to sort using foreign key field in django and avoid multiple results of same row如何在 django 中使用外键字段进行排序并避免同一行的多个结果
【发布时间】:2021-11-26 07:44:58
【问题描述】:

我想使用模型 GroupUser 中的“is_favorite”布尔字段对组进行排序。我有两个模型 GroupUser,其中有一个 Group 模型的外键,现在当我查询 Group.objects.filter(is_active=True).order_by('groupuser__group_id__is_favorite') 我多次获得团体。我尝试在最终查询集上使用 distict() 仍然没有运气。请提出任何其他方式或可能的解决方案。 TIA。

class Group(models.Model):
 
    group_name = models.CharField(
        max_length=250)

    context_type = models.ForeignKey(
        "contenttypes.ContentType",
        on_delete=models.DO_NOTHING,
        blank=True,
        null=True,
        related_name="content_type")

    context = models.IntegerField(
        blank=True,
        null=True)
        
    privacy_type = models.ForeignKey(
        "commans.PrivacyType",
        on_delete=models.DO_NOTHING,
        blank=True,
        null=True,
        related_name="group_privacy_id")
    
    is_active = models.BooleanField(
        default=True,
        help_text="Is Group Active")


class GroupUser(models.Model):

    group = models.ForeignKey(
        "Group",
        on_delete=models.DO_NOTHING,
        blank=True,
        null=True,
        related_name="groupuser_group_id")
    
    user=models.ForeignKey(
        "auth_module.User",
        on_delete=models.DO_NOTHING,
        blank=True,
        null=True)
    

    is_favorite = models.BooleanField(
        default=False, 
        blank=True,
        null=True)
```

【问题讨论】:

  • 您能否在问题中包含模型。您使用的是哪个数据库?
  • @Iain Shelvington:是的,已更新

标签: django orm django-queryset


【解决方案1】:

我们可以使用注解来计算每个组的收藏数量。然后我们可以使用这个注解来排序

from django.db.models import Sum

Group.objects.filter(
    is_active=True
).annotate(
    total_favorites=Sum('groupuser_group_id__is_favorite')
).order_by(
    '-total_favorites'
)

【讨论】:

  • 对不起,但发生的事情是我首先对组进行排序,但是当 is_favorite 值更改并且再次调用相同的 api 时,排序不起作用。我对每个组都有一个特定于用户的 is_favorite 行,因此可能无法使用 count、sum、max。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-27
  • 2017-05-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
相关资源
最近更新 更多