Django-Rest-Framework POST请求到ManyToMany字段 [英] Django-Rest-Framework POST request to ManyToMany Field

查看:471
本文介绍了Django-Rest-Framework POST请求到ManyToMany字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django模型,它是一条消息.它的名称是CharField,还有一个用户数组,即ManyToManyField.

I have a django model that is a message. It has a name which is a CharField, then also an array of users which is a ManyToManyField.

这就是我的API的样子:

So This is what my API looks like:

[
  {
    "id": 13,
    "content": "hej",
    "date": "2019-07-09",
    "sender": {
        "id": 1,
        "username": "william"
    }
  },
  {
    "id": 14,
    "content": "hej william",
    "date": "2019-07-09",
    "sender": {
        "id": 3,
        "username": "ryan"
    }
  }
]

我尝试通过邮递员POST发送的内容:

What I've tried to send via postman POST:

{
    "content": "Hello",
    "sender": {"username": "william"},
    "date": "2019-09-02"
}

我得到的错误:

sqlite3.IntegrityError: NOT NULL constraint failed: chat_message.sender_id

ManyToManyField(Userprofile = User):

ManyToManyField(Userprofile=User):

class Message(models.Model):
  sender = models.ForeignKey(UserProfile, on_delete=models.CASCADE, related_name="sendermessage")
  content = models.CharField(max_length=500)
  date = models.DateField(default=date.today)
  canview = models.ManyToManyField(UserProfile, blank=True, related_name="messagecanview")

class Meta:
    verbose_name_plural = 'Messages'

def __str__(self):
    return "{sender}".format(sender=self.sender)

推荐答案

假定已实现MessageSerializer类,则可以覆盖其create()方法以支持

Assuming that you have a MessageSerializer class implemented, you could override its create() method in order to support writable nested representations:

class MessageSerializer(serializers.ModelSerializer):
    ...

    def create(self, validated_data):
        sender_data = validated_data.pop('sender')
        sender = UserProfile.objects.create(**sender_data)
        return Message.objects.create(sender=sender, **validated_data)

您从字典中弹出发件人数据,创建一个在其中包含属性的UserProfile实例,然后将其附加到您的Message创作中.

You pop the sender data from the dictionary, create a UserProfile instance with the attributes in there and then attach it to your Message creation.

这将解决您的错误,因为现在在保存实际邮件之前 已创建了一个真实发件人.

This will resolve your error since now there is a real sender created before the actual message has been saved.

这篇关于Django-Rest-Framework POST请求到ManyToMany字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆