2016-01-22 46 views
0

這裏是我的串行 -DRF串行 - 名「自我」是沒有定義

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返回能夠顯示當前用戶而不是當前所有用戶。

回答

1

這是因爲你不能在字段定義中使用self(與模型字段相同)。自我沒有定義。如果我理解正確,你想返回當前用戶的用戶名。

class WidgetListSerializer(EncryptedLookupModelSerializer): 
    owner = serializers.SerializerMethodField() 
    ... 

    def get_owner(self, obj): 
     return self.context['request'].user.username 
+0

此方法的問題是它從POST選項中刪除該字段。我仍然希望看到POST中的Parent選項,但我只希望它顯示登錄用戶擁有的值。 – whoisearth