Django Queryset基于request.user的动态字段值

时间:2015-08-31 11:45:24

标签: django django-models django-views django-queryset django-managers

我有一个返回链接列表的网络服务。

{
     [
         {"id":1,"href":"http://website.com","title":"Title1"},
         {"id":2,"href":"http://website.com","title":"Title2"},
         {"id":3,"href":"http://website.com","title":"Title1"}
     ]
}

现在我想扩展它以返回字段voted,它会告诉我用户是否已经投票支持此链接。

{
     [
         {"id":1,"href":"http://website.com","title":"Title1","voted": "True"},
         {"id":2,"href":"http://website.com","title":"Title2","voted": "False"},
         {"id":3,"href":"http://website.com","title":"Title1","voted": "True"},
     ]
}

实现这一目标的最佳途径是什么?

我已经创建了模型方法voted(self),但我不认为这是最适合这样做的地方,但仍然无法访问我的request.user模特课。

 links\model.py ----------------------------------------

class Link(models.Model):
    href = models.URLField()
    title = models.CharField(max_length=400)

def voted(self, request):
    vote = UserVotes.objects.get(link_id=self.link.id, user_id=request.user)
    if vote == 1:
        return True
    else:
        return False

--------------------------------------------------------

 votes\model.py ----------------------------------------

class UserVotes(models.Model):
    user = models.ForeignKey(Account, blank=False)
    link = models.ForeignKey(Link, blank=False)
    vote = models.FloatField(null=True, blank=False)

    class Meta(object):
        unique_together = ('user', 'link')

--------------------------------------------------------

 link\serializers.py -----------------------------------

class LinkSerializer(serializers.ModelSerializer):
    voted = serializers.BooleanField()

    class Meta:
        model = Link

        fields = ('id', 'href', 'title','voted')
        read_only_fields = ('id', 'href', 'title', 'voted')

--------------------------------------------------------

1 个答案:

答案 0 :(得分:1)

您可以向序列化程序添加只读'voted' SerializerMethodField

这会将一个键voted添加到对象的序列化表示中。

来自SerializerMethodField文档:

  

它可用于向序列化添加任何类型的数据   你的对象的表示。

     

它应该返回您希望包含在序列化中的任何内容   对象的表示。

class LinkSerializer(serializers.ModelSerializer):
    voted = serializers.SerializerMethodField(method_name='has_user_voted') # add a 'voted' field

    class Meta:
        model = Link

        fields = ('id', 'href', 'title','voted')
        read_only_fields = ('id', 'href', 'title', 'voted')

    def has_user_voted(self, obj):
        user = self.context['request'].user # get the request object from context
        user_votes = UserVotes.objects.filter(user=user, link=obj)
        if user_votes:
            return True # return True if any user_votes object exists
        return False # otherwise return False