我看到這個錯誤,只是一個簡單的集成測試。該django應用程序被稱爲storageadmin
與稱爲Disk
模型與自定義模型方法稱爲pool_name
。我正在使用南和Django休息框架,並有SOUTH_TESTS_MIGRATE = False
在settings.py
Django fixtures和AttributeError:'QuerySet'對象沒有屬性<custom_model_method>
夾具是用此命令創建的。在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'
該代碼工作正常,問題只是在測試它時。