python - How to optimize number of queries in the Django view? -


i show comments in topic detail view. 2 queries happens in view: 1 topic , 1 comments list. understand select_related technique can't used here since there 2 different querysets created in view. there way decrease number of queries one?

application code follows below.

app/models.py

class topic(models.model):      headline = models.charfield(max_length=400)     description = models.textfield()     created = models.datetimefield(auto_now_add=true)     modified = models.datetimefield(auto_now=true)     author = models.foreignkey(user, related_name='topics')  class comment(models.model):      headline = models.charfield(blank=true, max_length=400)     description = models.textfield()     created = models.datetimefield(auto_now_add=true)     modified = models.datetimefield(auto_now=true)     author = models.foreignkey(user, related_name='comments')     topic = models.foreignkey(topic, related_name='comments') 

app/views.py

class topicdetail(detailview):      queryset = topic.objects.select_related('author').all()     context_object_name = 'topic'      def get_context_data(self, **kwargs):          context = super().get_context_data(**kwargs)         topic = self.object         context['comments'] = topic.comments.select_related('author').all()         return context 

app/templates/app/topic_detail.html

{{ topic.headline }} {{ topic.description }} {{ topic.created }} {{ topic.modified }} {{ topic.author }} {% comment in comments %}     {{ comment.headline }}     {{ comment.description }}     {{ comment.author }} {% endfor %} 

even in pure sql such "single" query hard.

basically need repeat topic data in each comment! in pseudo code:

select comment.*, topic.* comments right join topic 

that massive data processing/transfer overhead. whole operation should take more time, resources separate queries.

if need it, write custom function in comment topic model, pure sql.


Comments

Popular posts from this blog

IF statement in MySQL trigger -

c++ - What does MSC in "// appease MSC" comments mean? -

android - MPAndroidChart - How to add Annotations or images to the chart -