django orm过滤并按相关日期字段排除

django orm filter and exclude by related date field

models.py

class Model(models.Model):
    ...


class RelatedModel(models.Model):
    model = models.ForeignKey(Model, related_name="related_model")
    date = models.DateField()


我想按月和年过滤 DateField 实现的对象。

有什么解释吗?

谢谢。


文档中的答案:

Nota

The behavior of filter() for queries that span multi-value relationships, as described above, is not implemented equivalently for exclude(). Instead, the conditions in a single exclude() call will not necessarily refer to the same item.

For example, the following query would exclude blogs that contain both entries with «Lennon» in the headline and entries published in 2008:

Blog.objects.exclude( entry__headline__contains='Lennon', entry__pub_date__year=2008, )

However, unlike the behavior when using filter(), this will not limit blogs based on entries that satisfy both conditions. In order to do that, i.e. to select all blogs that do not contain entries published with «Lennon» that were published in 2008, you need to make two queries:

Blog.objects.exclude( entry__in=Entry.objects.filter( headline__contains='Lennon', pub_date__year=2008, ), )

同一个 Model 有多个 RelatedModel 个实例,其中一个可能 month=6 而另一个 year=2021。排除也会排除这些

documented一样,您必须准确过滤符合这两个条件的实例

Model.objects.exclude(
    related_model__in=RelatedModel.objects.filter(
        related_model__date__month=6,
        related_model__date__year=2021,
    ),
)