21

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?

1
  • 1
    What's happening is you're attempting to assign a many to many relationship before your message object actually exists. Try creating the message before assigning the users to it and it should work
    – MCBama
    Commented Dec 8, 2017 at 2:51

2 Answers 2

24

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
  • 1
    What purpose does the try / except block serve?
    – Bosco
    Commented Jun 23, 2018 at 3:01
  • 1
    just copied from the question
    – Vadym
    Commented Jun 23, 2018 at 16:31
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.

2
  • Can you link to ParentalManytoManyField in the Django docs pls?
    – alias51
    Commented Oct 6, 2021 at 22:20
  • I just saw that the ParentalManytoManyField is a variant of the standard django ManyToManyField. The ParentalManytoManyField correlates to Wagtail CMS. Didn't recognize it.
    – NewAgeA
    Commented Oct 8, 2021 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.