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)
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.
- [Django]-Where is a good place to work on accounts/profile in Django with the Django registration app?
- [Django]-__init__() got an unexpected keyword argument 'mimetype'
- [Django]-How to serve media files on Django production environment?