【问题标题】:Django Many-to-Many relationship SQL update fieldsDjango 多对多关系 SQL 更新字段
【发布时间】:2012-12-01 10:15:05
【问题描述】:

我对 django 模型 sql 插入/更新有疑问。 我正在阅读官方教程,在第 5 章中,有一个带有作者的简单数据库, 书籍和出版商表。 Author 表有 3 个字段:first_name、last_name、email Book 表也有一些字段,例如:名称、出版商等,以及多对多的作者字段 与 Author 表的关系。现在我正在尝试手动执行,django admin app 正在做什么 在幕后。我想添加或更新与给定图书关联的作者。

我是这样开始的(在 shell 阶段):

from mysite.models import Book, Author

new_author1 = 'John Doe' # that first_name and last_name exists in Author table
new_author2 = 'Jane Doe' # that first_name and last_name exists in Author table    
b = Book.objects.get(pk=2) # a book with id 2 exists in a Book table
b.authors = (new_author1,new_author2) # ?? trying to add/associate authors names with a selected book (pk=2)
b.save()

这当然行不通,我不知道我错过了什么

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    您不能仅使用字符串将作者与书籍相关联。您必须首先从数据库中检索实际的 Author 对象,然后才能将它们与 Book 相关联。 Django ORM 不会根据字符串神奇地为您找到对象。它无法知道字符串的哪一部分是名字或姓氏,或者该字符串根本不是指作者姓名,而不是其他字段。您需要执行以下操作才能获取 Author 对象:

    new_author1 = Author.objects.get(first_name__exact='John', last_name__exact='Doe')
    

    这是假设已经创建了 John Doe,正如它在您的 cmets 中所说的那样。如果没有,您需要使用以下内容创建 Author 对象:

    new_author1 = Author.objects.create(first_name='John', last_name='Doe')
    

    (我没有型号代码,所以这是假设最合乎逻辑的设置)。

    【讨论】:

    • 好的...我缺少基础知识。我还意识到我可以通过 Author.pk 字段获取作者,例如 new_author1 = Author.objects.get(pk=2),然后是 b.authors.add(new_author1)。感谢您的回复。
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 2012-03-25
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 2017-01-30
    相关资源
    最近更新 更多