<<消息:标题>"需要具有用于字段“ id”的值。在使用这种多对多关系之前。 [英] "<Message: title>" needs to have a value for field "id" before this many-to-many relationship can be used.

查看:77
本文介绍了<<消息:标题>"需要具有用于字段“ id”的值。在使用这种多对多关系之前。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个消息模型,其中有 create_user ForeignKey和 receive_user ManyToManyField:

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

我得到了例外:

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

如何解决此问题?

推荐答案

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

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

之后的校验码


以下是可以使用$ b $执行的操作示例b Python API工具。请注意,如果您对多对多关系使用中间
模型,则某些相关经理的
方法被禁用,因此其中一些示例不适用于此类

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.

我必须先保存父模型,然后才能添加m2m值。检查以下内容

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)

这篇关于&lt;&lt;消息:标题&gt;&quot;需要具有用于字段“ id”的值。在使用这种多对多关系之前。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆