我有一个查询,目前它在shell中使用Django ORM正常工作:
>>> Place.objects.all()[0].images.filter(order=0)[0].filename
'y5IUMPyv.jpg'
但我不知道如何使用DRF的SerializerMethodField实现它。这是我在此期间使用的,直到我能弄明白:
class CardSerializer(serializers.Serializer):
image = serializers.SerializerMethodField()
@staticmethod
def get_image(obj):
for d in obj.images.all():
if d.order == 0:
return d.filename
这是"理想的"不起作用的方法,我不知道原因:
@staticmethod
def get_image(obj):
return obj.images.filter(order=0)[0].filename
Traceback (most recent call last):
File "/home/admin/env/lib/python3.4/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/admin/env/lib/python3.4/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/admin/env/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/home/admin/env/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "/home/admin/env/lib/python3.4/site-packages/rest_framework/views.py", line 466, in dispatch
response = self.handle_exception(exc)
File "/home/admin/env/lib/python3.4/site-packages/rest_framework/views.py", line 463, in dispatch
response = handler(request, *args, **kwargs)
File "/home/admin/env/lib/python3.4/site-packages/rest_framework/generics.py", line 201, in get
return self.list(request, *args, **kwargs)
File "/home/admin/env/lib/python3.4/site-packages/rest_framework/mixins.py", line 45, in list
return self.get_paginated_response(serializer.data)
File "/home/admin/env/lib/python3.4/site-packages/serpy/serializer.py", line 134, in data
self._data = self.to_value(self.instance)
File "/home/admin/env/lib/python3.4/site-packages/serpy/serializer.py", line 123, in to_value
return [serialize(o, fields) for o in instance]
File "/home/admin/env/lib/python3.4/site-packages/serpy/serializer.py", line 123, in <listcomp>
return [serialize(o, fields) for o in instance]
File "/home/admin/env/lib/python3.4/site-packages/serpy/serializer.py", line 107, in _serialize
result = getter(self, instance)
File "/home/admin/src/places/serializers.py", line 72, in get_image
return obj.images.filter(order=0)[0].filename
File "/home/admin/env/lib/python3.4/site-packages/django/db/models/query.py", line 297, in __getitem__
return list(qs)[0]
IndexError: list index out of range
答案 0 :(得分:2)
正如铁娘子@ anderson-lima指出的那样,这是你的数据而不是代码的问题。您没有order = 0的图像,并且如果不是最佳的话,您的第一个方法会处理这种情况。
NSLog
然而,在你的第二种方法中,你正在获取切片,但是获取一个不存在的对象。因此,执行,并反过来告诉我们你需要的只是一个尝试,除了块。
@staticmethod
def get_image(obj):
for d in obj.images.all():
if d.order == 0:
return d.filename
# returns None here if an object with order = 0
# does not exist in the database.