Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tastypie属性&;相关名称,空属性错误_Python_Django_Tastypie - Fatal编程技术网

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

Python Tastypie属性&;相关名称,空属性错误,python,django,tastypie,Python,Django,Tastypie,我得到了这个错误: The object '' has an empty attribute 'posts' and doesn't allow a default or null value. 我正在尝试获取帖子上的“投票数”,并将其返回到my models.py中: class UserPost(models.Model): user = models.OneToOneField(User, related_name='posts') date_created = mode

我得到了这个错误:

The object '' has an empty attribute 'posts' and doesn't allow a default or null value.
我正在尝试获取帖子上的“投票数”,并将其返回到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)
以下是我的资源:

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

我做错了什么?

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

定义一种脱水方法:

def dehydrate(self, bundle):
    bundle.data['custom_field'] = bundle.obj.get_votes()
    return bundle
或者将
get_vots
设置为属性,并在resource中这样定义字段(我建议使用此字段,因为它最清晰):

或者这样定义:

votes = fields.CharField(readonly=True, null=True)
在参考资料中,定义脱水投票方法如下:

def dehydrate_votes(self, bundle):
    return bundle.obj.get_votes()

您的第二个解决方案奏效了,尽管我有点好奇-我的resources.py如何知道get_vots指的是my models.py中的一个方法?这就是Tastypie的工作方式吗?如果使用Tastypie中的ModelResources,则
属性将引用模型的属性。准确地说,这是在现场脱水过程中完成的,如下所示:
def dehydrate_votes(self, bundle):
    return bundle.obj.get_votes()