Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

python - Django Getting QuerySet.values() based on condition

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

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

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...