Django ORM 查询优化问题

Django ORM Query Optimization Issue

我正在制作一个博客网站,我遇到了一些查询性能问题。

我有3个模型

  1. 用户模型 -> 用户(存储用户电子邮件、密码等)
  2. Post 模型 -> 实际 Posts
  3. people 模型 -> (存储用户额外信息)

Post 型号 ->

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    category = models.ForeignKey(Category, on_delete=models.PROTECT)
    title = models.CharField(max_length=255,null=True)   
    description = models.CharField(max_length=1000,null=True)
    Likes = models.ManyToManyField(to=User, related_name='Post_likes')
    favourites = models.ManyToManyField(to=User,blank=True,related_name="favourite")

人物模型 ->

class People(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    photo = models.ImageField(upload_to='profile_pics', blank=True,null=True)
    Phone_number = models.CharField(max_length=255,null=True,blank=True)
    Birth_Date = models.DateField(null=True,blank=True)
    Created_date = models.DateTimeField(auto_now_add=True)
    Updated_date = models.DateTimeField(auto_now=True)

现在这两个模型都连接到用户模型。我想查询 Post 模型并在模板中获取用户照片。现在,当我使用 post.user.people.photo 时,对于每个 post,它都会生成一个单独的数据库查询,导致运行缓慢。我想在这里使用Join来合并多个表并一次获取所有记录。

我目前正在使用以下查询 ->

posts =  Post.objects.select_related().prefetch_related('images_set').annotate(comments_Count = Count('comments_post',distinct=True)).annotate(Count('Likes',distinct=True)).all().order_by('-id')

您可以在 userpeople 上使用 user__people 执行 .select_related(…) [Django-doc],因此:

posts = Post.objects.select_related(
    <strong>'user__people'</strong>, 'category'
).prefetch_related('images_set').annotate(
    comments_Count = Count('comments_post',distinct=True),
    Count('Likes',distinct=True)
).order_by('-id')

Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.