5

Let's say I have a model Class Parent and a Class Child. And child has a field called status and a ForeignKey relationship to Parent.

Let's say I retrieve one parent by calling filter (so as to have a QuerySet) by calling p = Parent.objects.filter(pk=1)

Now if I call p.values('children__name') I will receive a list of dictionaries of the children names to that parent.

My question is, if I wanted to call p.values('children__name') but limit the values only if the status of the child was specific, how would I do that?

I also want to make sure the original QuerySet is unaltered, as I don't want to filter it down (for larger QuerySets). I just want to filter the values that are based on some parameter.

Is there any way to do this in Django?

2 Answers 2

12

You would just filter:

p.filter(children__status='whatever').values('children__name')
Sign up to request clarification or add additional context in comments.

3 Comments

I do not wish to alter the original QuerySet (which this does). So for example, if I want to list all the parents and children that have a status of 'SICK' then I cannot just do what you did because it would filter down the parents to that. I wish to still keep all the parents, just have the value of 'children__name' be filtered down to those with a specific status. Does that make sense?
This gets Parents who have any children with a status 'whatever' and then gets all the children names of these parents. That gets you children of other statuses as well, if they had a "sibling" with the status 'whatever'
works fine for me
0

You can filter child values on M2M relationships using Prefetch. Prefetch specifies how to get data from the through table between Parent and Child and prefetch_related triggers the actual query.

from django.db.models import Prefetch

pf = Prefetch('children', Child.objects.filter(status='SICK')
parents = Parent.objects.filter(pk=1).prefetch_related(pf)

sick_children_names = []
for parent in parents:
    sick_children_names.append([child.name for child in parent.children.all()])

Alternative approach would be to use the through table itself.

names = Parent.children.through.objects.filter(parent_id=1, child__status='SICK').values('children__name')

Or with an existing qs p:

names = Parent.children.through.objects.filter(parent_id__in=p, child_status='SICK').values('children__name')

More on M2M throughs here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.