Django-Rest-Framework POST request to ManyToMany F

2019-08-24 17:27发布

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.

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"
    }
  }
]

What I've tried to send via postman POST:

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

The Error I get:

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

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)

1条回答
虎瘦雄心在
2楼-- · 2019-08-24 17:41

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)

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.

查看更多
登录 后发表回答