开发者

Minimize mysql database hits from django query

开发者 https://www.devze.com 2023-01-23 17:41 出处:网络
I am making a query in django that ends up hitting the database 4 times.I want to be sure that there\'s no more efficient way of pulling the data than I already am doing.

I am making a query in django that ends up hitting the database 4 times. I want to be sure that there's no more efficient way of pulling the data than I already am doing.

I have a model:

class Film(models.Model):
   studio = models.ForeignKey(Studio)
   name = models.CharField(max_length=30)
   rating = models.ForeignKey(Rating)
   actor = models.ManyToManyField('Actor', blank=True, related_name='actor', db_table=u'moviedb_film_actor')
   staff = models.ManyToManyField(Staff, blank=True, through='Association')

My view is here:

def film_by_id(request, id):

   # Look up the car name (and raise a 404 if it can't be found).
   object = get_object_or_404(film.objects.select_related(), id__iexact=id)

   template_name = 'Film_by_id.html',

   association_objects = Association.objects.select_related(depth=1).filter(Q(film__name=object.name))
   source_objects = Source.objects.filter(film__name=object.name)

   object.association_objects = association_objects
   object.trim_objects = trim_objects

   return render_to_response(
        template_name,
        {"object" : object},
        context_instance = RequestContext(request))

And finally, my template:

Make: {{ object.studio }}<br>
Rating: {{ object.rating }}<br><br>

<u>--Actors--</u><br>
{% for actor in object.actor.all %}
    {{ actor.name }}<br>
{% endfor %}
<br>

<u>--Staff-开发者_Python百科-</u><br>
{% for item in object.association_objects %}
    {{ item.staff.name }} - {{ item.get_type_display }}<br>
{% endfor %}

<u>--Source--</u><br>
<ul>
{% for item in object.source_objects %}
    <li>{{ item }}
{% endfor %}
</ul>

The debug toolbar indicates that I'm hitting the database 4 times. The problem sees to be the ManytoMany fields and the "reverse select_related" I'm trying to execute with Source.

So the initial data pull hits once

Referencing Actor hits once

Referencing Association_objects hits once

Referencing Source hits once

So overall, is there a way to reduce the database hits? Specifically, is there a better way to pull the many-to-many relations without creating more simultaneous database queries?


You could eliminate the lookups for Association and Source if you were to use a ForeignKey relationship between them. Then select_related could pull these as well.

If you really, deeply care about optimizing the ManyToManyField I would suggest caching the result of the lookup.

0

精彩评论

暂无评论...
验证码 换一张
取 消