I’m getting this error:
The object '' has an empty attribute 'posts' and doesn't allow a default or null value.
I’m trying to get the number of ‘votes’ on a post and return it in my models.py:
class UserPost(models.Model):
user = models.OneToOneField(User, related_name='posts')
date_created = models.DateTimeField(auto_now_add=True, blank=False)
text = models.CharField(max_length=255, blank=True)
def get_votes(self):
return Vote.objects.filter(object_id = self.id)
Here’s my resource:
class ViewPostResource(ModelResource):
user = fields.ForeignKey(UserResource,'user',full=True)
votes= fields.CharField(attribute='posts__get_votes')
class Meta:
queryset = UserPost.objects.all()
resource_name = 'posts'
authorization = Authorization()
filtering = {
'id' : ALL,
}
What am I doing wrong?
The
attributevalue that you have defined isn’t proper.You can achieve what you want in a few ways.
Define a
dehydratemethod:Or set the
get_votesas property and define the field in resource like so (I recommend this one as it is the most clear):Or define it this way:
And in the resources define the dehydrate_votes method like so: