ali.m.n.2003
ali.m.n.2003

Reputation: 43

N+1 query optimization problem with Django custom user

I override the Django's built-in user django.contrib.auth.user and I created app called core for this purpose I override it like this in core/models.py path:

from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    email = models.EmailField(unique=True)

also I changed the corresponds form and django admin.

by the way I have store app which is contain several models, but problem is the every model of my store app need to go and create separately query for each user in database. here is my customer and comment model:

class Customer(models.Model)
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name='customer')
    phone_number = models.CharField(max_length=11)
    birth_date = models.DateField(null=True, blank=True)
    datetime_created = models.DateTimeField(auto_now_add=True)
    favourite = models.ManyToManyField(Product, related_name='favourite', blank=True)

and my comments model is:

class Comment(models.Model)
    class Status(models.TextChoices):
        waiting = 'w', 'Waiting'
        approved = 'a', 'Approved'
        not_approved = 'na', 'Not Approved'
    
    author = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='comments')
    body = models.TextField()
    raiting = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)], blank=True, null=True)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='comments')
    status = models.CharField(max_length=2, choices=Status.choices, default=Status.waiting)
    datetime_created = models.DateTimeField(auto_now_add=True)

I use this query in drf ModelViewSet for catch the comments with it's corresponding author:

def get_queryset(self):
        product_pk = self.kwargs["product_pk"]
        return Comment.objects.select_related('author__user').filter(product_id=product_pk).all()

but in debug toolbar still I have multiple similar queries and here there are:

SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 1 LIMIT 21
 7 similar queries.

SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 2 LIMIT 21
 7 similar queries.

SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 3 LIMIT 21
 7 similar queries.

SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 4 LIMIT 21
 7 similar queries.

SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 5 LIMIT 21
 7 similar queries.

SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 6 LIMIT 21
 7 similar queries.

SELECT ••• FROM `core_customuser` WHERE `core_customuser`.`id` = 7 LIMIT 21
 7 similar queries.

please help!

The N+1 query problem when create custom user in Django

Upvotes: 0

Views: 62

Answers (0)

Related Questions