I have a webservice that returns list of links.
{
[
{"id":1,"href":"http://website.com","title":"Title1"},
{"id":2,"href":"http://website.com","title":"Title2"},
{"id":3,"href":"http://website.com","title":"Title1"}
]
}
Now I want to extend it to return also field voted
, which will tell me if user has already voted for this link or not.
{
[
{"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"},
]
}
What is the best way to achive that?
I've created model method voted(self)
, but I don't think this is the best place for doing that, and still I don't have access to request.user in my model class.
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')
--------------------------------------------------------