Context: Foo is a class that has a foreignKey field pointing to a Bar object. Several Foos may refer to the same Bar. (Many to one)
I need to reference several fields of a Foo object’s foreignkey (Bar.field and Bar.field2), but it seems that each time I do so it runs a separate query.
As a result, referencing these fields can take forever.
Is there a way to get all the Bar objects in a single query? Or is there a better way to speed it up?
foo_list = Foo.objects.filter(params) # takes 0.001 sec, returns 10k objects
result = []
for f in foo_list:
# this part takes 40 seconds due to the huge number of queries
bar = f.bar # Foo contains a foreignKey reference to the Bar class
result.append({
"field": f.field,
"barField": bar.barField,
"barField2": bar.barField2,
# this way was even worse
# "barField": f.bar.barField,
# "barField2": f.bar.barField2,
})
does the job. The rest of the code would remain the same, but
would use the cached objects