Question

I have a project.

project = Project.objects.get(id=1)

and now i want to select the data from related tables of project. It can be done it 2 ways, let me know which one is better. and why?

attachments = project.attachments_set.all() samples = project.projectsamples_set.all()

OR

attachments = Attachments.objects.filter(project=ctx['project']) samples = ProjectSamples.objects.filter(project=ctx['project'])

I would like to know the Technical prospective.

Was it helpful?

Solution

These queries are exactly equivalent, as you can see if you examine the generated SQL. I would say that the first is preferable as it is more compact and readable, but that is very much subjective so it is up to you which you use.

(Note that if you don't actually have the project object to start with, and don't need it, then it's more efficient to query Attachments and Samples via project_id than to get the product and use the related accessors. However that doesn't appear to be the case in your example.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top