过滤多个具有DateRange字段作为“ validity_range”的模型

时间:2019-03-12 06:17:17

标签: python django django-models

使用Django ORM,我有多个模型(A,B,C,A2B,B2C),它们都从代表其有效期的ValidityMixinModel继承。

class ValidityMixinModel(models.Model):
    validity_range = DateRangeField(null=True, blank=True)
    class Meta:
        abstract = True

class A(ValidityMixinModel):
    Bs = models.ManyToManyField("B", through="A2B")


class B(ValidityMixinModel):
    As = models.ManyToManyField(A, through="A2B")
    Cs = models.ManyToManyField("C", through="B2C")

class C(ValidityMixinModel):
    Bs = models.ManyToManyField(B, through="B2C")


class A2B(ValidityMixinModel):
    a = models.ForeignKey(A, related_name="Bs_through", on_delete=models.CASCADE)
    b = models.ForeignKey(B, related_name="As_through", on_delete=models.CASCADE)

class B2C(ValidityMixinModel):
    b = models.ForeignKey(B, related_name="Cs_through", on_delete=models.CASCADE)
    c = models.ForeignKey(C, related_name="Bs_through", on_delete=models.CASCADE)

我希望能够以一种简单的方式过滤在给定日期有效的所有对象(A,B,C,A2B,B2C),例如:

with ValidityMixinModel.valid_on_context_manager(date(2018,11,23)):
    # only display objects A with their related Bs 
    # as if A, B and A2B instances had all the filter 
    # validity_range__contains=DateRange(date(2018,11,23),date(2018,11,24))
    print(A.objects.prefetch_related("Bs","Bs_Cs").all())

关于如何执行此操作的任何想法?

0 个答案:

没有答案