gpt4 book ai didi

python - Django fixtures 和 AttributeError : 'QuerySet' object has no attribute

转载 作者:行者123 更新时间:2023-11-28 20:21:45 27 4
gpt4 key购买 nike

我在一个简单的集成测试中看到了这个错误。 Django 应用名为 storageadmin,带有一个名为 Disk 的模型和一个名为 pool_name 的自定义模型方法。我正在使用 South 和 django rest 框架,并且在 settings.py

中有 SOUTH_TESTS_MIGRATE = False

夹具是用这个命令创建的。默认数据库在转储数据之前由应用程序填充了一些模型,刚好足以进行测试。

./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'

有一个在 View 中用于发送响应的序列化器

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

class Meta:
model = Disk

View 返回这样的响应

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

编辑:如正确答案所示,问题出在上面的 View 中。我使用的是非常旧的 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'

代码运行良好,问题仅在测试时出现。

最佳答案

如错误所说,您正在传递一个查询集,但您并没有告诉 DRF 您正在做什么。你需要通过 many=True :

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

关于python - Django fixtures 和 AttributeError : 'QuerySet' object has no attribute <custom_model_method>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26637305/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com