如何处理连字符和Django rest ModelSerializer

How to deal with Hyphen and Django rest ModelSerializer

我正在尝试实施端点以接收来自 mailgun.com API 的电子邮件。基本上,当电子邮件发送到邮件列表时,他们会通过 POST 请求调用您的端点 https://host/messages/

问题在于它们不使用标准 REST,并且某些键包含连字符。这是我收到的请求示例:

{
  'Date': [
    'Fri, 26 Apr 2013 11:50:29 -0700'
  ],
  'From': [
    'Bob <bob@sandbox9cbe4c2829ed44e98c8ebd0c26129004.mailgun.org>'
  ],
  'Sender': [
    'bob@sandbox9cbe4c2829ed44e98c8ebd0c26129004.mailgun.org'
  ],
  'Subject': [
    'Re: Sample POST request'
  ],
  'To': [
    'Alice <alice@sandbox9cbe4c2829ed44e98c8ebd0c26129004.mailgun.org>'
  ],
  'body-plain': [
    'Hi Alice,\n\nThis is Bob.\n\nI also attached a file.\n\nThanks,\nBob\n\nOn 04/26/2013 11:29 AM, Alice wrote:\n> Hi Bob,\n>\n> This is Alice. How are you doing?\n>\n> Thanks,\n> Alice\n\n'
  ],

我写了一个序列化并设法获得所有没有连字符的字段,例如 FromTo 等。但是经过数小时的试验,我无法获得 body-plain

我试过这个:

class MessageSerializer(serializers.ModelSerializer):
    Text = serializers.CharField(source='body-plain')

    class Meta:
        model = Message
        fields = ['From', 'To', 'Subject', 'Text']

但我收到错误 {"Text":["This field is required."]}

在我看来,Django rest 可能正在修改键。有人知道如何处理这个问题吗?

我找到了一个可以帮助其他人解决这个问题的解决方法。虽然,我仍然不明白为什么我在问题中的代码不起作用。如果你有更好的方法,我还在找:)

--

想法是在 ViewSet 中覆盖 POST 上的创建并绕过 ModelSerializer

class MessageViewSet(viewsets.ModelViewSet):
    queryset = Message.objects.all()
    serializer_class = MessageSerializer

    def perform_create(self, serializer):
        msg = Message.objects.create(Subject=self.request.data['Subject'], To=self.request.data['To'], From=self.request.data['From'], Text=self.request.data['stripped-text'])
        msg.save()


class MessageSerializer(serializers.ModelSerializer):
    Text = serializers.CharField(source='body-plain')

    class Meta:
        model = Message
        fields = ['From', 'To', 'Subject', 'Text']
        read_only_fields = ['Text']


class Message(BaseModel):
    From = models.CharField(max_length=500)
    To = models.CharField(max_length=500)
    Subject = models.CharField(max_length=500)
    Text = models.CharField(max_length=10000)
    timestamp = models.DateTimeField(auto_now=True)