Django过滤相关字段(Django filter related field)

我有相关的模型

class Profile: # some fields # related model class Plan: profile = models.ForeignKey(Profile, related_name='plans') start = models.DateField()

我希望能够过滤个人资料的计划。 例如,我想获取所有配置文件,但只选择尚未启动的计划。

是否有可能实现这种行为? 此代码不会返回将来没有计划的配置文件。 这是行为不是我正在寻找的。 我想获取所有配置文件并过滤他们的计划。

Profile.objects.filter(plans__start__gte =现在())

即使其中一些已经启动,它也将返回Profile的所有计划。

I have related models

class Profile: # some fields # related model class Plan: profile = models.ForeignKey(Profile, related_name='plans') start = models.DateField()

I want to be able to filter profile's plans. For example I want to get all the profiles, but only select the plans that haven't started yet.

Is it possible to achieve such behavior? This code will not return Profiles that don't have plans in the future. And this is behavior is not what I'm looking for. I want to get all the profiles and filter their plans.

Profile.objects.filter(plans__start__gte=now())

Also it will return all the plans for Profile even if some of them started already.

最满意答案

尝试使用Prefetch ,这将为您提供所有配置文件,但其中的计划将按标准日期过滤:

plans = Plan.objects.filter(start__gte=now()) profiles = Profile.objects.prefetch_related(Prefetch('plans', queryset=plans)).all()

Try to use Prefetch, this will give you all profiles but plans inside it will be filtered by stard date:

plans = Plan.objects.filter(start__gte=now()) profiles = Profile.objects.prefetch_related(Prefetch('plans', queryset=plans)).all()

更多推荐