Django queryset(基于同一模型中其他字段的过滤器)

时间:2018-08-05 21:54:20

标签: django django-queryset

class PriceRepository(models.Model):
    product = models.ForeignKey(Product, related_name='price_repo')

    price = models.DecimalField('price of product', max_digits=7, decimal_places=2)

    location = models.ForeignKey(Location, on_blank=True, null=True, related_name='price_repo')

    is_default = models.BooleanField()

这是我的模型课。我想创建一个查询集,以便我选择一个价格,如果指定了位置,并且如果产品不存在这样的记录,那么我要选择具有is_default设置的价格。

假设始终存在一个默认价格。

PriceRepository.objects.filter(location__id=1)返回价格为location.id = 1的记录。我想返回PriceRepository中所有产品的默认价格 ,如果location.id = 1丢失

我该如何解决这个问题?

解决方案: 在罗曼·雅库波维奇(Roman Yakubovich)输入之后,

query_set = PriceRepository.objects.filter(product=interested_product)
                                   .annotate(wished_price=Case(When(location=self.location, then=F('price')),
                                              When(is_default=True, then=F('price')),
                                              default=Value(-1),
                                              output_field=DecimalField(max_digits=7, decimal_places=2)))
                                   .filter(wished_price__gt=0)

1 个答案:

答案 0 :(得分:1)

尝试基于Case expressions的此解决方案(目前无法对其进行测试,因此可能会出现一些错误):

from django.db.models import Case, When, Value, F, DecimalField

PriceRepository.objects.annotate(wished_price=Case(
    When(location__id=1, then=F('price')), 
    default=Value(default_price), 
    output_field=DecimalField(max_digits=7, decimal_places=2))
)
相关问题