在使用此多对多关系之前,“ <消息:标题>”必须具有字段“ id”的值。

fanhualuojin154873 :

我有一个消息模型,并且在其中有create_userForeignKey和receive_userManyToManyField:

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

使用波纹管保存消息时,除了一个例外:

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.

如何解决这个问题?有朋友可以帮我吗?

zvadym:

Django文档:https//docs.djangoproject.com/zh-CN/1.11/topics/db/examples/many_to_many/

之后检查代码

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

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

    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)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何定位具有使用Thymeleaf组成的ID的输入字段的值

ValueError:“在使用此多对多关系之前,需要具有字段“ id”的值”

显示具有多对多关系的字段laravel 5.4

Laravel具有自定义表名称和ID的多对多关系

查询多对多关系确定值的所有记录

Yii2:使用多对多关系的值填充模型字段

typeorm:保存具有多对多关系ID的实体

是否可以在消息和标题中引用除id字段之外的其他字段?

使用JS设置所有具有X ID的输入字段的值

Django-在使用这种多对多关系之前,需要具有字段“ id”的值

Django:遇到错误说“需要使用字段“ id”才能使用这种多对多关系”

<News:somethinng>”必须具有字段“ id”的值,然后才能使用这种多对多关系

具有多个ID的多对多关系

Django AttributeError:<Object>必须具有字段“ id”的hvalue,然后才能使用这种多对多关系

在Sequelize中使用具有多对多关系的AND运算

如何从具有一定条件的多对多关系中获取所有值

删除时:ValueError:在使用此多对多关系之前,“ <用户:测试用户(testuser)>”需要具有字段“ id”的值

Django模型错误:可以使用此多对多关系之前的字段x

MySQL-一个字段中有多个值或多对多关系?

ValueError:“ <Notification:Notification object>”必须具有字段“ notification”的值,然后才能使用多对多关系

使用JPA映射具有属性的多对多关系

访问具有更多行多对多关系的 SQL Select 值

ValueError:变量需要具有字段“id”的值才能使用这种多对多关系 - Django

如何修复“ValueError: "<Klant: None - aCustomer>" 需要有字段 "klant" 的值才能使用这种多对多关系。”

如何在具有多对多关系的查询中添加 id 数组 Sequelize

使用 Dapper 构建具有多对多关系的对象

"<Order: Order object (None)>" 需要有字段 "id" 的值才能使用这种多对多关系

使用值列表过滤多对多关系

在使用这种多对多关系之前,django use mixin 需要有字段“id”的值