如何通过``注释''添加变量,该变量负责当前用户在模型字段之一的值列表中的存在

问题描述

我有以下模型:

class ProfilePost(models.Model):
    author = models.ForeignKey(Profile,on_delete=models.CASCADE)
    post_text = models.TextField(max_length=10000)
    publication_date = models.DateTimeField(auto_Now_add=True)
    like = models.ManyToManyField(Profile,related_name='like')

class Profile(models.Model):
    user = models.OnetoOneField(User,on_delete=models.CASCADE,primary_key=True)
    profile_picture = models.ImageField(default='/pictures/default.png',upload_to='pictures/',blank=True)
    city = models.CharField(max_length=63,blank=True)
    phone = models.CharField(max_length=15,blank=True)

和这个view.py

class ProfileViewWithPk(LoginrequiredMixin,View):
    login_url = '/login/'
    form_class = PostCreationForm
    template_name = 'userprofile/userProfile.html'

    def get(self,request,user_id,*args,**kwargs):
        user = get_object_or_404(User,id=user_id)
        if request.GET and request.GET['request_type'] == 'get_extra_posts':
            posts2 = ProfilePost.objects.filter(author=user.profile).order_by('-publication_date')
            posts_with_users_likes = list(request.user.profile.like.all().values_list('id',flat=True))
            print(posts_with_users_likes) # [21,11,10,8,6,1]
            posts2 = posts2.annotate(
            like_count=Count('like',distinct=True),comment_count=Count('postcomment',is_liked_by_user=Value(len(Q(id__in=posts_with_users_likes)),output_field=BooleanField())
            )
            posts2 = posts2.values('id','post_text','publication_date','is_liked_by_user','like_count','comment_count')
            print(posts2)
            return JsonResponse(data={'posts': posts2})

在我的views.py中,我想向ProfilePost Queryset添加一些额外的字段,但是我在is_liked_by_user字段上遇到了问题,如果当前用户喜欢此字段,则该字段为True发布,否则发布False。

print(posts2)输出

 <QuerySet [{'id': 12,'post_text': '6','publication_date': datetime.datetime(2020,1,18,2,29,635769,tzinfo=<UTC>),'like_count': 0,'comment_count': 0,'is_liked_by_user': True},{'id': 11,'post_text': '5',21,401305,'like_count': 1,{'id': 10,'post_text': '4',49,402443,'comment_count': 1,{'id': 9,'post_text': '3',17,59,945073,{'id': 8,'post_text': '2',46,9,141195,{'id': 7,'post_text': '1',45,48,182141,{'id': 1,'post_text': 's',28,22,23,156756,'like_count': 2,'comment_count': 7,'is_liked_by_user': True}]>

但是is_liked_by_user仅对ID为[21,1]的帖子为True。我在做什么错了?

Django 3.1版

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)