这是我的序列化程序 -
class WidgetListSerializer(EncryptedLookupModelSerializer):
owner = serializers.SlugRelatedField(
slug_field='username',
queryset=MyAppUser.objects.filter(user=self.context['request'].user),
default = serializers.CurrentUserDefault())
parent = serializers.SlugRelatedField(
slug_field='name',
queryset=WidgetList.objects.all())
class Meta:
model=WidgetList
fields = ('id', 'name', 'description', 'owner', 'parent')
我得到以下追溯:
Traceback:
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
119. resolver_match = resolver.resolve(request.path_info)
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
365. for pattern in self.url_patterns:
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns
401. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/opt/myproject_app/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
395. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.7/importlib/__init__.py" in import_module
37. __import__(name)
File "/opt/myproject/myproject/urls.py" in <module>
20. from gui import views
File "/opt/myproject/gui/views.py" in <module>
20. from api.serializers import *
File "/opt/myproject/api/serializers.py" in <module>
52. class WidgetListSerializer(EncryptedLookupModelSerializer):
File "/opt/myproject/api/serializers.py" in WidgetListSerializer
56. queryset=MyAppUser.objects.filter(user=self.context['request'].user),
Exception Type: NameError at /api/widgetlists/
Exception Value: name 'self' is not defined
我基本上希望序列化程序只在POST HTML中返回显示当前用户的能力,而不是当前所有用户。
答案 0 :(得分:1)
那是因为你不能在字段定义中使用self(与模型的字段相同)。自我没有定义。如果我理解正确,您想要返回当前用户的用户名。
class WidgetListSerializer(EncryptedLookupModelSerializer):
owner = serializers.SerializerMethodField()
...
def get_owner(self, obj):
return self.context['request'].user.username