Django reverse lookup chaining queryset

梦想与她 提交于 2019-12-06 21:30:29

If you're just after the images associated with a particular designer, you can grab them with a single query:

designer = Designer.objects.get(id=id)
images = UploadedImage.objects.filter(product__designer=designer)

If you would like to associate them with the project, there's a couple of ways to do that.

If there aren't many different projects, and you're concerned about querying the database too much, you can use the images list from before, and perform the filtering in python:

images = list(images) # Crystallise the query
projectImages = [[img for img in images if img.project == p]
                 for p in designer.project_set.all()]

However, a better way to do it would probably be to let the database handle the filtering; for sets of a non-trivial size it will likely be faster.

That way, you can just query for the images directly, ie:

designer = Designer.objects.get(id=id)
projects = designer.project_set.all() # Project.objects.filter(designer=designer)
projectImages = [UploadedImage.objects.filter(project=p) for p in projects]

The big advantage of the second approach is that the elements in projectImages are still query sets, so can still be further filtered or annotated.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!