我有一个“事件”模型,它有一个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
但是,我收到的错误就像在下面的图片中一样
//这是我用过的APIView
答案 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
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)
urlpatterns = [
url(r'^users/(?P<user_id>\d+)',EventView.as_view())
]