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

aro*_*ooo 2 python django tastypie

我收到这个错误:

The object '' has an empty attribute 'posts' and doesn't allow a default or null value.
Run Code Online (Sandbox Code Playgroud)

我试图在帖子上获得"投票"的数量并将其返回到我的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)
Run Code Online (Sandbox Code Playgroud)

这是我的资源:

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,
            }
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Ani*_*cha 6

attribute已定义的值不正确.您可以通过几种方式实现自己想要的目标.

定义dehydrate方法:

def dehydrate(self, bundle):
    bundle.data['custom_field'] = bundle.obj.get_votes()
    return bundle
Run Code Online (Sandbox Code Playgroud)

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

votes = fields.CharField(attribute='get_votes', readonly=True, null=True)
Run Code Online (Sandbox Code Playgroud)

或者这样定义:

votes = fields.CharField(readonly=True, null=True)
Run Code Online (Sandbox Code Playgroud)

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

def dehydrate_votes(self, bundle):
    return bundle.obj.get_votes()
Run Code Online (Sandbox Code Playgroud)