Effective Django Query

Django's slightly new way of doing things, but I have a series of loops that I'm sure can be done more efficiently. Essentially, I have a group of related objects that I need to expand the graph to get values ​​from the object connected at the end. I loop the objects to eventually get the values ​​I need. See below code:

for media in campaign.media_set.all(): media_key = media.key for target in media.target_set.all(): x = target.x y = target.y target_id = target.id for metatag in target.metatag_set.all(): body = metatag.body hdr = metatag.header ftr = metatag.footer ct_url = metatag.clickthrough point_url = metatag.point.image_file 

Any pointers to a way to do this with less DB choice?

+4
source share
3 answers

Yes, you are walking along it back. This is a problem that I have had many times when working with Django. The easiest way is to start with the object you want to receive and work back to meet all conditions. those. it looks like you want information on this metatag , so start with this one.

 MetaTag.objects.filter(conditions_here) 

And then, to get other things like this x / y target, just use the related_name automatic properties created on the metatag object. It's hard to say for sure without seeing your models.

+4
source

All in all, it's great to read: https://docs.djangoproject.com/en/dev/topics/db/optimization/

Maybe just add select_related before your initial search can help a lot.

+1
source

It is almost impossible to answer without seeing the definition of the model. If this is a ForiegnKey relationship, you can most likely completely eliminate the outer loops and just generate all your data by following the foreign keys up (using select_related, of course, to get all the data at once)

However, most likely, we are looking at many many relationships, and for this you cannot just move the backups of foreign keys, and the answer you have may be the best you can do.

0
source

All Articles