Django灯具和AttributeError:&#39; QuerySet&#39;对象没有属性<custom_model_method> </custom_model_method>

时间:2014-10-29 17:46:48

标签: python django django-rest-framework django-fixtures

我通过简单的集成测试看到了这个错误。 django应用程序称为storageadmin,其模型名为Disk,其自定义模型方法称为pool_name。我使用的是南方和django休息框架,SOUTH_TESTS_MIGRATE = False

中有settings.py

使用此命令创建夹具。在dumpdata之前,应用程序会使用一些模型填充默认数据库,这足以进行测试。

./bin/django dumpdata storageadmin oauth2_provider auth.User --indent=2 > src/rockstor /storageadmin/fixtures/storageadmin.json

该错误涉及以下模型

class Disk(models.Model):
    pool = models.ForeignKey(Pool, null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=10, unique=True)    

def pool_name(self, *args, **kwargs):
    try:
        return self.pool.name
    except:
        return None

class Meta:
    app_label = 'storageadmin'

在视图中使用了一个序列化程序来发送响应

class DiskInfoSerializer(serializers.ModelSerializer):
    pool_name = serializers.CharField(source='pool_name')

    class Meta:
        model = Disk

视图返回类似的响应

ds = DiskInfoSerializer(Disk.objects.all())
return Response(ds.data)

编辑:如正确答案中所示,问题出在上述视图中。我使用的是非常旧的DRF(2.1.15),但目前正在测试的版本(2.4.3)需要 ds = DiskInfoSerializer(Disk.objects.all(), many=True)

触发错误的简单测试用例是:

class DiskTests(APITestCase):
    fixtures = ['storageadmin.json']
    BASE_URL = '/api/disks/scan'

    def test_disk_scan(self):
        self.client.login(username='admin', password='admin')
        response = self.client.post(self.BASE_URL, data=None, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

最后,错误是

File "/opt/rock-dep/src/rockstor/storageadmin/views/disk.py", line 88, in _scan
    return Response(ds.data)
File "/opt/rock-dep/eggs/djangorestframework-2.4.3-py2.7.egg/rest_framework   /serializers.py", line 572, in data
    self._data = self.to_native(obj)
File "/opt/rock-dep/eggs/djangorestframework-2.4.3-py2.7.egg/rest_framework/serializers.py", line 351, in to_native
    value = field.field_to_native(obj, field_name)
File "/opt/rock-dep/eggs/djangorestframework-2.4.3-py2.7.egg/rest_framework/fields.py", line 336, in field_to_native
    return super(WritableField, self).field_to_native(obj, field_name)
File "/opt/rock-dep/eggs/djangorestframework-2.4.3-py2.7.egg/rest_framework/fields.py", line 207, in field_to_native
    value = get_component(value, component)
File "/opt/rock-dep/eggs/djangorestframework-2.4.3-py2.7.egg/rest_framework/fields.py", line 58, in get_component
    val = getattr(obj, attr_name)
AttributeError: 'QuerySet' object has no attribute 'pool_name'

代码工作正常,问题出在测试时。

1 个答案:

答案 0 :(得分:8)

就像错误所说的那样,您传递了一个查询集,但是您并没有告诉DRF您正在做什么。您需要通过many=True

ds = DiskInfoSerializer(Disk.objects.all(), many=True)