如何根据子表的数量对Django中的查询值进行排序?

问题描述 投票:0回答:1

我有一个

Product
班级,其中有一个子班级
ProductColors

这是我的两门课:

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, allow_unicode=True)
    description = models.TextField()
    price = models.PositiveIntegerField()
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    discount = models.PositiveIntegerField(default=0)
    offer_end = models.DateTimeField(blank=True, null=True)
    user_likes = models.ManyToManyField(User, related_name="product_likes", blank=True)


class ProductColor(models.Model):
    class ColorChoices(models.TextChoices):
        RED = "#f50b0b","قرمز"
        BLUE = "#0844f3","آبی"
        YELLOW ="#f7f704", "زرد"
        GREEN = "#22f704","سبز"
        PINK = "#f704e8","صورتی"
        PURPLE = "#901f89","بنفش"
        GRAY = "#9c939c","خاکستری"
        WHITE = "#ffffff","سفید"
        BLACK = "#000000","سیاه"
        ORANGE = "#f2780c","نارنجی"
        BROWN =  "#513924","قهوه ای"
        GLASS = "#f3f3f2", "بی رنگ"

    product = models.ForeignKey(Product, related_name='colors', on_delete=models.CASCADE)
    color = models.CharField(choices=ColorChoices.choices, max_length=255)
    quantity = models.PositiveIntegerField(default=0)

    def __str__(self):
        return f"{self.product.name} - {self.color}"

我正在尝试首先根据可用情况对产品进行排序,然后根据颜色数量从较高数量到零进行排序。

我尝试用这种方法做到这一点:

from django.db.models import Count, When, Case, IntegerField


products = Product.objects.all().order_by('-available', 'name')
products = products.annotate(
        has_zero_quantity=Case(
            When(colors__quantity=0, then=1),
            When(colors__quantity__gt=0, then=0),
            output_field=IntegerField(),
        )
    )

但我陷入困境,找不到正确的方法 - 谁能帮我找到解决方案?

python django postgresql django-orm
1个回答
0
投票

我找到了答案,我想与一些可能像我一样陷入困境的人分享:

from django.db.models import Prefetch
products = products.filter(available=True).prefetch_related(
        Prefetch('colors', queryset=ProductColor.objects.order_by('-quantity'))
    )

解决问题

© www.soinside.com 2019 - 2024. All rights reserved.