S
S
Stanislav2020-12-12 14:56:29
Django
Stanislav, 2020-12-12 14:56:29

Is it possible to reduce the number of queries to the database using ORM?

For each comment, a throw to the database is created, and if the comment is with a photo, then 2 requests. Comments have 2 levels of nesting. Is it possible to reduce the number of requests using ORM?
models.py

class Comment(models.Model):
    post = models.ForeignKey(
        Post, on_delete=models.CASCADE, blank=False, null=False, related_name='comments')
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, blank=False, null=False)
    parent = models.ForeignKey(
        'self', on_delete=models.CASCADE, blank=True, null=True, related_name='children')
    text = models.CharField(max_length=1000, blank=False, null=False, verbose_name='комментарий')

class Photo(models.Model):
    comment = models.ForeignKey(
        Comment, null=True, blank=True,  on_delete=models.CASCADE, related_name='user_photos')
    photo = models.ImageField(upload_to='user-photo/')

templatestags/comments.py
@register.inclusion_tag('comment/comments.html')
def comments(post: 'Queryset[Post]'):
    comments = Comment.objects.filter(
        post=post).prefetch_related('user_photos', 'children').select_related('user', 'parent')

    return {
        'comments': comments,
        'name': post.name
    }

comment/comments.html
{% for i in comments %}
    {% if not i.parent %}
            {{ i.text }}
            {% if i.user_photos.all %}
                {% for img in i.user_photos.all %}
                    <img src="{{ img.thumb.url }}">
                {% endfor %}
            {% endif %}
            {% if i.children %}
                {% for child in i.children.all %}
                    {{ child.text }}
                    {% for img in child.user_photos.all %}
                        <img src="{{ img.thumb.url }}">
                    {% endfor %}
                {% endfor %}
            {% endif %}
    {% endif %}
{% endfor %}

Wrapping Comment.objects.filter in a list or iterating through for in doesn't help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-12-12
@Chebaa

Can. Foreign keys have select_related , and hierarchies have mptt .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question