Reputation: 5066
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?
Upvotes: 2
Views: 2568
Reputation: 1796
The attribute
value that you have defined isn't proper.
You can achieve what you want in a few ways.
Define a dehydrate
method:
def dehydrate(self, bundle):
bundle.data['custom_field'] = bundle.obj.get_votes()
return bundle
Or set the get_votes
as property and define the field in resource like so (I recommend this one as it is the most clear):
votes = fields.CharField(attribute='get_votes', readonly=True, null=True)
Or define it this way:
votes = fields.CharField(readonly=True, null=True)
And in the resources define the dehydrate_votes method like so:
def dehydrate_votes(self, bundle):
return bundle.obj.get_votes()
Upvotes: 6