'collections.OrderedDict'对象没有属性'username'

时间:2016-11-22 01:27:30

标签: django django-rest-framework django-serializer

我有一个“事件”模型,它有一个many2many字段,默认用户模型。

class Event(models.Model):
    name = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    location = models.CharField(max_length=255)
    start_hour = models.CharField(max_length=50)
    end_hour = models.CharField(max_length=50)
    creator = models.CharField(max_length=50)
    info = models.CharField(max_length=255, default='')
    users = models.ManyToManyField(User)

    def __str__(self):
        return self.name

现在,我正在尝试更新此many2many字段,如下所示;

//my serializers

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id',)


class EventSerializer(serializers.ModelSerializer):
    users = UserSerializer(many=True)

    class Meta:
        model = Event
        fields = ('id', 'users')

    def update(self, instance, validated_data):
        submitted_users = validated_data.get('users')
        if submitted_users:
            for user in submitted_users:
                user_instance = User.objects.get(id=user.id)
                instance.users.add(user_instance)
        instance.save()
        return instance

//views.py

class UpdateParticipants(generics.RetrieveUpdateDestroyAPIView):
    queryset = Event.objects.all()
    serializer_class = EventSerializer

但是,我收到的错误就像在下面的图片中一样

enter image description here

//这是我用过的APIView

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以尝试使用以下代码吗?

模型

实施例

@echo off
Diskpart.exe /s D:\script.txt

串行

class UserModel(User):
    pass

class Event(models.Model):
    name = models.CharField(max_length=50)
    type = models.CharField(max_length=50)
    location = models.CharField(max_length=255)
    start_hour = models.CharField(max_length=50)
    end_hour = models.CharField(max_length=50)
    creator = models.CharField(max_length=50)
    info = models.CharField(max_length=255, default='')
    users = models.ManyToManyField(User, related_name='event_user') # Set related name to User object for Rest Framework

    def __str__(self):
        return self.name

浏览

class EventSerializer(serializers.ModelSerializer):
    users = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), required=False)
    class Meta:
        model = Event
class Userserializer(serializers.ModelSerializer):
    event_user = EventSerializer(many=True)
    class Meta:
        model = UserModel

    def update(self, instance, validated_data):
        event_user = validated_data.pop('event_user', None)
        print (event_user)

        if validated_data:
            for attr, value in validated_data.items():
                if attr == 'password':
                    instance.set_password(value)
                else:
                    setattr(instance, attr, value)
            instance.save()
        return instance

URL-S

class EventView(APIView):
    permission_classes = (AllowAny,)

    def get(self):
        qv = User.objects.all()
        serializer = Userserializer(qv, many=True)
        return Response(data={'users': serializer.data}, status=status.HTTP_200_OK)

    def put(self, request, user_id):
        instance = Event.objects.get(user=user_id)
        serializer = Userserializer(instance=instance,data=request.data, partial=True)
        if serializer.is_valid(raise_exception=True):
            serializer.save()
            return Response(data={'users': serializer.data}, status=status.HTTP_200_OK)
        return Response(data={'users': serializer.errors}, status=status.HTTP_403_FORBIDDEN)  

JOSN exaple for put

JSON

urlpatterns = [

    url(r'^users/(?P<user_id>\d+)',EventView.as_view())
]