Django 条件 ORM 查询

Django Conditional ORM Query

我正在创建一个博客网站,用户可以在其中为每个博客喜欢或不喜欢 post。 现在,每次用户进入索引页面时,我都想更改“喜欢”按钮,即如果用户喜欢 post 然后不喜欢按钮,否则喜欢按钮。 为此,我需要从 views.py 文件中获取变量 IsLiked

这是我写的查询。

posts =  Post.objects.exclude(users=request.user).select_related('user__people','ProductAvailability').prefetch_related('images_set').annotate(comments_Count = Count('comments_post',distinct=True)).annotate(Count('Likes',distinct=True)).all().order_by('-id')

for post in posts:
        if(post.Likes.filter(id=user_id).exists()):
            isLiked = True
        else:
            isLiked = False

这里的问题是对于每个 post 都有一个单独的查询发送到数据库。

这是我的博客Post模特->

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT)
    # category = models.ForeignKey(Category, on_delete=models.PROTECT)
    ProductAvailability = models.ForeignKey(ProductAvailability, on_delete=models.PROTECT, null=True, blank=True)
    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")
    Tag1 = models.CharField(max_length=255,null=True,blank=True)
    Tag2 = models.CharField(max_length=255,null=True,blank=True)
    Tag3 = models.CharField(max_length = 255, null = True, blank = True)
    Tag1_Name = models.CharField(max_length=255,null=True,blank=True)
    Tag2_Name = models.CharField(max_length=255,null=True,blank=True)
    Tag3_Name = models.CharField(max_length=255,null=True,blank=True)
    users = models.ManyToManyField(User, related_name='users_hidden_from_post')
    Created_date = models.DateTimeField(auto_now_add=True)
    Updated_date = models.DateTimeField(auto_now=True)

PS: 请忽略Post模型中的冗余信息

我想通过查询发送用户 ID 并检查用户是否喜欢个人 post。

您可以使用条件 is_liked 注释 Post,检查 User 是否出现在带有 Post 之类的直通模型中=29=]:

from django.db.models import Exists, OuterRef

posts = Post.objects.exclude(
    users=request.user
).select_related(
'user__people', 'ProductAvailability'
).prefetch_related(
    'images_set'
).annotate(
    comments_Count = Count('comments_post',distinct=True),
    Count('Likes',distinct=True),
    is_liked=<strong>Exists(</strong>
        Post.Likes.through.objects.filter(
            post_id=OuterRef('pk'), user_id=<em>user_id</em>
        <strong>)</strong>
    )
).order_by('-id')

如果 user_id 出现在 Likes 中,则由此查询集产生的 Post 对象将有一个名为 .is_liked 的额外属性,即 True为此 Post.


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.


Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: likes instead of Likes.