Django多对多关系SQL更新字段

时间:2012-12-13 13:52:08

标签: python django django-models

我有django model sql insert / update的问题。 我正在阅读官方教程,在第5章中有一个简单的数据库与作者, 书籍和发布者表格。 Author表有3个字段:first_name,last_name,email Book表也有一些字段,如:name,publisher等,以及具有多对多的作者字段 与作者表的关系。现在我正在尝试手动操作,django管理员应用程序正在做什么 在幕后。我想添加或更新与给定书籍相关联的作者。

我是这样开始的(在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()

这当然不起作用,我不知道我错过了什么

1 个答案:

答案 0 :(得分:2)

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

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

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

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

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

相关问题