基于 ManyToManyField 值的 Django Order QuerySet

Django Order QuerySet based on ManyToManyField value

我的商业模式如下:

class Business(models.Model):

    class Meta:
        verbose_name_plural = "Businesses"

    name = models.CharField(max_length=60, null=False, verbose_name="Title")
    about = models.TextField(max_length=5000, null=True, verbose_name="Description", blank=True)
    upvote = models.ManyToManyField(Account, verbose_name="Upvote Count", blank=True)

账户模型如下:

class Account(models.Model):

    CHOICES = [('Male', 'Male'),Female', 'Female'),]

    class Meta:
        verbose_name_plural = "Accounts"

    name = models.CharField(max_length=60, null=False, verbose_name="Title")
    gender= models.CharField(max_length=6, null=True, verbose_name="Gender", choices=CHOICES)

我正在尝试获取将按帐户性别排序的查询集。

如何实现?

到目前为止,我已经实现了按赞数排序。

Business.objects.all().order_by("upvote")

您可以通过双下划线访问相关模型的文件。请参阅文档 here

尝试:

Business.objects.all().order_by("upvote__gender")

您可以使用 Sum function [Django docs] with a Conditional Expression [Django docs] 来注释您将根据其排序的值:

from django.db.models import Case, Sum, Value, When

Business.objects.annotate(
    order_value=Sum(
        Case(
            When(upvote__gender='Male', then=Value(1)),
            When(upvote__gender='Female', then=Value(-1)),
            default=Value(0)
        )
    )
).order_by('order_value')

上面的查询会给你 Business 个对象,女性优先,男性优先,你可以通过写 .order_by('-order_value') 来颠倒顺序。