【问题标题】:django postgresql join operation querydjango postgresql 连接操作查询
【发布时间】:2013-12-27 08:44:53
【问题描述】:

我有如下所示的 Django 模型,我需要创建一个视图,我必须在其中获取 post.id、post.title、post.description、owner.name、该帖子 id 的点赞数。如何制作获取所有这些详细信息的单个查询?有什么建议吗?

class Post(models.Model):
    title=models.CharField(max_length=150)
    description=models.TextField()
    owner=models.ForeignKey("User")

class User(models.Model):
    name=models.CharField(max_length=200)
    location=models.CharField(max_length=200)

class comment(models.Model):
    post_id=models.ForeignKey("Post", null=True,blank=True)
    user_id=models.ForeignKey("USER")

// #likes may be for post or for comment
class likes(models.Model):
    post_id=models.ForeignKey("Post", null=True,blank=True)
    comment_id=models.ForeignKey("comment", null=True,blank=True)
    user_id=models.ForeignKey("USER")

【问题讨论】:

    标签: django postgresql join


    【解决方案1】:

    您可以使用select_related 在单个查询中加入用户模型,并使用annotate 计算给定帖子的点赞数:

    from django.db.models import Count
    
    my_id = 42
    post = Post.objects.select_related('owner') \
        .annotate(num_likes=Count('likes')) \
        .get(id=my_id)
    

    然后您可以访问这些值:

    post.id
    post.title
    post.description
    post.owner__name
    post.num_likes
    

    【讨论】:

      猜你喜欢
      • 2016-03-28
      • 2014-02-07
      • 2019-05-20
      • 2012-10-14
      • 1970-01-01
      • 2021-08-30
      • 1970-01-01
      • 2022-08-18
      • 2017-06-30
      相关资源
      最近更新 更多