【问题标题】:Find data inside the nested ORM in Django在 Django 的嵌套 ORM 中查找数据
【发布时间】:2020-02-15 05:29:50
【问题描述】:
class Post(models.Model):
    POST_TYPE =(
        ("video","video"),
        ("pic","pic"),
    )
    upload_by = models.ForeignKey(User,on_delete=models.CASCADE)
    caption = models.TextField()
    post_type = models.CharField(max_length=100,choices=POST_TYPE)
    media = models.FileField(upload_to='posts/')
    created_at = models.DateTimeField(auto_now_add=True)


class PostLikes(models.Model):
    post = models.ForeignKey(Post,on_delete=models.CASCADE)
    like_by = models.ForeignKey(User,on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

这是我的 models.py 文件,我想知道当前登录用户是否喜欢我的模板中的帖子。我在我的模板文件中这样做

{% if request.user in i.postlikes_set.all%}

但我知道这是错误的,任何人都可以解决这个问题吗? 我想在我的模板中这样做

<a class="post-like-btn" href="#" {% if request.user in i.postlikes_set.all%} style="color: #e16a70;" {% else %} style="color:#b2b2b2 !important;" {% endif %}>

【问题讨论】:

    标签: django python-3.x django-models django-templates django-views


    【解决方案1】:

    恕我直言,检查用户是否喜欢Post 是需要在视图中完成的操作。

    查看您的帖子,我认为您在模板中显示了Posts 的列表,其中每个项目都被用户喜欢或不喜欢。您可以做的是在视图中使用此信息注释每个帖子,然后在您的模板中使用此信息。例如

    #views.py
    
    from django.db.models import OuterRef, Exists
    
    def list_posts(request):
        user = request.user
    
        my_likes = PostLikes.objects.filter(
            post = OuterRef('pk'),
            like_by = user
        )
    
        posts = Post.objects.annotate(like_by_user=Exists(my_likes))
    
        context = {'posts': posts}
    
        return render(request, 'yourtemplate.html', context)
    

    然后在你的模板中你可以做

    <a class="post-like-btn" href="#" {% if i.like_by_user %} style="color: #e16a70;" {% else %} style="color:#b2b2b2 !important;" {% endif %}
    

    【讨论】:

      猜你喜欢
      • 2021-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多