我有一个返回链接列表的webservice。
{
[
{"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)
,但我不认为这是最好的地方这样做,我仍然没有访问请求。用户在我的模型类。
linksmodel.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
--------------------------------------------------------
votesmodel.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')
--------------------------------------------------------
linkserializers.py -----------------------------------
class LinkSerializer(serializers.ModelSerializer):
voted = serializers.BooleanField()
class Meta:
model = Link
fields = ('id', 'href', 'title','voted')
read_only_fields = ('id', 'href', 'title', 'voted')
--------------------------------------------------------
可以将只读的'voted'
SerializerMethodField
添加到序列化器中。
这将在对象的序列化表示中添加一个键voted
。
From SerializerMethodField
docs:
可用于向序列化对象中添加任何类型的数据对象的表示。
它应该返回任何您想要包含在序列化的对象的表示。
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