Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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. So for example, if I want to list all the parents and children that have a status of 'SICK' then I do not want to call p.filter(children__status='SICK').values('children__name') because that will filter the parents. 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?

Is there any way to do this in Django?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

p = Parent.objects.filter(age=50)
sick_children = p.filter('children__status='sick').values('children__name')

The queryset will not be modified unless you assign the filter to p.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...