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

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

大家好,我有一个产品类,它有一个子类 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.