Django Filtering Specific QuerySet.values()

2020-04-21 03:05发布

问题:

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?

回答1:

You would just filter:

p.filter(children__status='whatever').values('children__name')


回答2:

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