[Django]-"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.

23đź‘Ť

âś…

Django documentation: https://docs.djangoproject.com/en/1.11/topics/db/examples/many_to_many/

Check code after

What follows are examples of operations that can be performed using
the Python API facilities. Note that if you are using an intermediate
model for a many-to-many relationship, some of the related manager’s
methods are disabled, so some of these examples won’t work with such
models.

My must save parent model first, and only after that you can add m2m values. Check below

    receive_user = User.objects.get(id=user_id)
    message = Message.objects.create(
        title=title,
        content=content,
        create_user=create_user,
        # receive_user=receive_user,
    )
    # message.save() - no needs in save() when you use create() method
    message.receive_user.add(receive_user)
👤Vadym

2đź‘Ť

Another way to get around with creating a relation to another model while creating it, is to relate to the model by ParentalManyToManyField .

With this its possible to save simultaneously the id of the instance and relate to another model.

from modelcluster.fields import ParentalManyToManyField

receive_user = ParentalManyToManyField(User, related_name="received_messages", help_text="接受者")

Maybe this could help.

👤NewAgeA

Leave a comment