简体   繁体   中英

Django Many-to-Many relationship SQL update fields

I have a problem with django model sql insert/update. I'm going through the official tutorial, and in Chapter 5 there's a simple database with Authors, Books and Publisher tables. The Author table has 3 fields: first_name, last_name, email The Book table has some fields too, like: name, publisher etc. and authors field with Many-to-Many relationship with Author table. Now I'm trying to do manually, what django admin app is doing behind the scenes. I want to add or update authors that are associated with given book.

I've started like this (at the shell stage):

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()

This is of course not working and i don't know what i'm missing

You cannot associate authors with books using only strings. You have to retrieve the actual Author objects from the database first, then you can associate them with the Book. The Django ORM will not magically find the objects for you based on the strings. There's no way for it to know what part of the string is the first name or the last name, or that the string refers to an Author name at all, as opposed to some other field. You need to do something like this to get the Author objects:

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

This is assuming the John Doe has already been created, as it says in your comments. If not, you need to create the Author object with something like:

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

(I don't have the model code, so this is assuming the most logical setup).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM