过滤相关模型

时间:2017-03-14 09:45:20

标签: django django-models django-templates

请参阅下面的我的模型(3个型号:Variant,Deal和Campaign)。

我想获得一个变种列表及其相关交易,其广告系列的开始日期为今天。

我已经能够过滤广告系列的开始日期,但是,正在退回的交易列表未被过滤。

    def get_queryset(self):

    """

        Override get_queryset to cater for dynamic filtering

    """

    date_filters = []

    from_date = self.request.GET.get('from', None)

    if from_date is not None and len(from_date) > 0:
        date_filters.extend([Q(deal_set__campaign_start_date__gte=parse_date(from_date)),])
    else:
        date_filters.extend([Q(deal_set__campaign_start_date__gte=now()),])

    to_date = self.request.GET.get('to', None)

    if to_date is not None and len(to_date) > 0:
        date_filters.extend([Q(deal_set__campaign_end_date__lte=parse_date(to_date)),])

    return Variant.objects.filter(*date_filters).distinct()

class Variant(BaseModel):

    """

    Product model

    """

    variant_id = models.AutoField(primary_key=True)
    unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
    value = models.DecimalField(max_digits=3, decimal_places=2, default=Decimal('0.0'))
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

class Deal(BaseModel):

    """

    Deal model

    """

    deal_id = models.AutoField(primary_key=True)
    price = models.DecimalField(max_digits=4, decimal_places=2)
    variant = models.ForeignKey(Variant, on_delete=models.CASCADE)
    campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE)

class Campaign(BaseModel):

    """

    Campaign model

    """

    campaign_id = models.AutoField(primary_key=True)
    start_date = models.DateField(default=now())
    end_date = models.DateField(default=now())
    store = models.ForeignKey(Store, on_delete=models.CASCADE)

1 个答案:

答案 0 :(得分:0)

您想拥有所有变体或只有具有广告系列开始日期的交易吗?

对于后者,它应该是这样的:

from datetime import date

Variant.objects.filter(deal_set__campaign__start_date=date.today())

如果需要,请将其与select_related结合使用。