Tastypie属性&相关名称,空属性错误

时间:2012-09-19 10:51:38

标签: python django tastypie

我收到了这个错误:

The object '' has an empty attribute 'posts' and doesn't allow a default or null value.

我试图在帖子中获得“投票”的数量并将其返回到我的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)

这是我的资源:

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,
            }

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您定义的attribute值不合适。 你可以通过几种方式实现自己想要的目标。

定义dehydrate方法:

def dehydrate(self, bundle):
    bundle.data['custom_field'] = bundle.obj.get_votes()
    return bundle

或者将get_votes设置为属性并在资源中定义字段,如此(我推荐这个,因为它是最清晰的):

votes = fields.CharField(attribute='get_votes', readonly=True, null=True)

或者用这种方式定义:

votes = fields.CharField(readonly=True, null=True)

在资源中定义了dehydrate_votes方法,如下所示:

def dehydrate_votes(self, bundle):
    return bundle.obj.get_votes()
相关问题