How to deal with Hyphen and Django rest ModelSerializer

為{幸葍}努か 提交于 2019-12-13 20:54:10

问题


I am trying to implement an endpoint to receive email from the mailgun.com API. Basically, when an email is sent to the mailing list, they call your endpoint https://host/messages/ with a POST request.

The problem is that they do not use standard REST and some of the keys contain hyphens. This is an example of the request I receive:

{
  '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'
  ],

I write a serialize and manage to get all fields without hyphens such as From, To, etc. But after hours of trials I cannot manage to get the body-plain.

I tried this:

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

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

but I get the error {"Text":["This field is required."]}

It seems to me that Django rest is perhaps modifying the keys. Does someone know how to deal with this problem?


回答1:


I found a work around that might help others with this issue. Though, I still do not understand why my code in the question does not work. If you have a better way, I am still looking :)

--

The idea is to override the creation on POST in the ViewSet and bypass the 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)


来源:https://stackoverflow.com/questions/59013211/how-to-deal-with-hyphen-and-django-rest-modelserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!