【问题标题】:Django-Rest-Framework 'str' object has no attribute 'id'Django-Rest-Framework 'str' 对象没有属性 'id'
【发布时间】:2018-09-13 02:37:23
【问题描述】:

我正在 DRF 中创建一个调用以 POST 到该站点。我有点困惑为什么我会收到这个错误。我不明白为什么这期望它是一个str。我知道有类似的帖子,但它们仍然无法解决。

错误

AttributeError: 'str' object has no attribute 'id'
[03/Apr/2018 10:55:12] "POST /api/user/UserProfile/1/ HTTP/1.1" 500 83982

serializer.py 看起来像,如果我删除 instance.id 我会得到同样的错误,但只是针对下一行。

from rest_framework import serializers
from api.models import UserProfile
from django.contrib.auth.models import User


class UserProfileSerializer(serializers.Serializer):
    # id = serializers.UUIDField()
    class Meta:
        model = UserProfile

    def create(self, validated_data):
        return UserProfile.objects.create(**validated_data)

    def update(self, instance, validated_data):
        instance.id = validated_data.get('profile_id', str(instance.id))
        instance.user_id = validated_data.get('user_id', instance.user_id)
        instance.save()
        return instance

查看

@csrf_exempt
def user_profile_list(request, user_id):
    try:
        userid = user_id
    except userid.DoesNotExist:
        return HttpResponse(status=404)

    if request.method == 'GET':
        uprofile = UserProfile.objects.all().values()
        list2 = list(uprofile)
        return JsonResponse(list2, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = UserProfileSerializer(userid, data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

urls.py

url(r'^api/user/UserProfile/(?P<user_id>[0-9]+)/$', userprofile.user_profile_list),

【问题讨论】:

  • 错误信息很清楚,调试你的代码,看看为什么instance得到str
  • django noob....不知道该怎么做
  • 那么请阅读the debugger docs,这是一个很好的了解工具!

标签: python django python-3.x django-rest-framework


【解决方案1】:

您传递给序列化程序 userid 而不是用户对象。要使用序列化程序更新对象,您应该将实例作为第一个参数传递。将视图更改为:

elif request.method == 'POST':
    data = JSONParser().parse(request)
    user = User.objects.get(id=userid)
    serializer = UserProfileSerializer(user, data=data)
    ...

【讨论】:

    【解决方案2】:

    属性错误

    问题在于serializer = UserProfileSerializer(userid, data=data) 行,您将userid 传递给序列化程序而不是用户用户配置文件实例,我说是因为逻辑对我来说不是很清楚(使用 UserProfileSerializer 但更新 User 实例?)。

    改进

    您尝试使用代码完成的工作可以通过更简单的方式完成:

    1. 使用ModelSerializer 代替序列化程序
    2. 使用ModelViewSet 而不是基于函数的视图 (user_profile_list)

    使用 ModelSerializer 和 ModelViewSet 的通用版本大致如下:

    序列化器.py

    from rest_framework import serializers
    from api.models import UserProfile
    
    
    class UserProfileSerializer(serializers.ModelSerializer):
        class Meta:
            model = UserProfile
            # preferably listing the fields to avoid any code breaking
            # if you add fields to the model later on
            fields = '__all__'
    

    views.py

    from rest_framework import viewsets
    
    from api.serializers import UserProfileSerializer
    from api.models import UserProfile
    
    
    class UserProfileViewSet(viewsets.ModelViewSet):
        queryset = UserProfile.objects.all()
        serializer_class = UserProfileSerializer
    

    我强烈建议您通过DRF's official tutorial,如果您了解您的应用程序的哪些部分已经在 DRF 中实现并且可以用很少的代码直接使用,它将为您节省大量的开发时间。

    【讨论】:

      猜你喜欢
      • 2015-10-15
      • 2019-04-30
      • 2017-03-04
      • 2021-05-02
      • 2020-12-24
      • 2022-09-23
      • 2011-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多