Reputation: 553
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.
Upvotes: 0
Views: 786
Reputation: 47374
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()
Upvotes: 1