我正在尝试使用django-rest-framework序列化器ModelSerializer类创建django模型实例。这是我的序列化器代码:
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
fields = ['sender', 'chat_room', 'content', 'sending_date']
这是我尝试使用其创建模型实例时的观点:
class SendMessage(APIView):
authentication_classes = [authentication.TokenAuthentication]
permission_classes = [permissions.IsAuthenticated]
def post(self, request):
try:
message_type = request.data['message_type']
if message_type == ('text' or 'image' or 'audio'):
if message_type == 'text':
message_serializer = MessageSerializer(sender=request.user, chat_room=ChatRoom.objects.get(
id=request.data['chat_room_id']), content=MessageContent(text=request.data['text']))
message = Message(message_serializer.data)
elif message_type == 'image':
message = MessageSerializer(sender=request.user.id, chat_room=request.data['chat_room_id'],
content=MessageContent(image=request.FILES['image']))
elif message_type == 'audio':
message = MessageSerializer(sender=request.user.id, chat_room=request.data['chat_room_id'],
content=MessageContent(image=request.FILES['image']))
if message.chat_room.users.all().filter(id=request.user.id).exists():
message.save()
if message_type == 'image':
resize_photo(message.content.image, MessageContent.image_width, MessageContent.image_height)
if message_type == 'audio':
if (not message.content.name.lower().endswith('mp4')) and os.get_size(message.content) > 25000:
message.delete()
raise FileSourceError
message.save()
return Response(status=status.HTTP_201_CREATED)
else:
return Response(status=status.HTTP_401_UNAUTHORIZED)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
except KeyError or FileSourceError:
return Response(status=status.HTTP_400_BAD_REQUEST)
这是我的消息模型:
class Message(models.Model):
sender = models.ForeignKey(User, related_name='sender', on_delete=models.CASCADE)
chat_room = models.ForeignKey(ChatRoom, related_name='chat_room', on_delete=models.CASCADE)
content = models.OneToOneField(MessageContent, on_delete=models.CASCADE)
is_read_by = models.ManyToManyField(User, related_name="is_read_by")
sending_date = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('sending_date',)
但是,当我运行这段代码时,我得到了
TypeError: init ()得到了意外的关键字参数'sender'
如果删除sender参数,我将得到
TypeError: init ()获得了意外的关键字参数'chat_room'
,依此类推。我检查了我的ModelSerializer是否使用
做正确的序列化器字段 print(repr(MessageSerializer()))
在django python外壳中,我得到了
MessageSerializer():
sender = PrimaryKeyRelatedField(queryset=User.objects.all())
chat_room = PrimaryKeyRelatedField(queryset=ChatRoom.objects.all())
content = PrimaryKeyRelatedField(queryset=MessageContent.objects.all(), validators=[<UniqueValidator(queryset=Message.objects.all())>])
sending_date = DateTimeField(read_only=True)
,这意味着我的序列化器具有以下字段(发件人,chat_room等) 为什么会出现此错误,以及如何解决?谢谢您的时间!
答案 0 :(得分:1)
您应该将Message
模型实例传递给MessageSerializer
或包含dict
中指定键的包含数据的fields
。
如果要传递dict
,请将dict
传递给data
关键字。
message_dict = {'sender': request.user, 'chat_room': ChatRoom.objects.get(id=request.data['chat_room_id']), 'content': MessageContent(text=request.data['text'])}
message_serializer = MessageSerializer(data=message_dict)
if message_serializer.is_valid():
message_serializer.save()
确保在create
中实现了MessageSerializer
方法。
答案 1 :(得分:0)
在 model.py 文件中,类属性之一发生更改
identification = models.IntegerField()
在 model.py 文件中,类属性之一发生更改
identification = models.IntegerField ()
不要在括号内留下任何内容,然后在控制台中使用以下命令进行检查
python manage.py check application_name