2

我收到此错误:

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

我究竟做错了什么?

4

1 回答 1

6

您定义的attribute值不正确。您可以通过几种方式实现您想要的。

定义一个dehydrate方法:

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

或者设置get_votesas 属性并像这样定义资源中的字段(我推荐这个,因为它最清楚):

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()
于 2012-09-19T12:01:45.483 回答