I have a Message model, And in it I have create_user
ForeignKey and receive_user
ManyToManyField:
class Message(models.Model):
"""
消息
"""
message_num = models.CharField(default=getMessageNum, max_length=16, help_text="消息") # 注意:message_num 相同,说明是同一次发送
title = models.CharField(max_length=64, help_text="消息名称")
content = models.CharField(max_length=1024, help_text="消息内容")
create_user = models.ForeignKey(User, related_name="created_messages",help_text="创建者")
receive_user = models.ManyToManyField(User, related_name="received_messages", help_text="接受者")
def __str__(self):
return self.title
def __unicode__(self):
return self.title
When I use the bellow to save a message, I except a exception:
try:
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()
except Exception as e:
raise e
I get the exception:
"<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.
How to resolve this issue? some friend can help me about this?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With