1👍
✅
if book is already there in database.
just simply run like
book_obj = Book.objects.get(title="Test Title") author1 = Author.objects.get(name="test author1") author2 = Author.objects.get(name="test author2") author3 = Author.objects.get(name="test author3") book_obj.authors.add(author1, author2, author3)
Same you can add Publisher if book is already in database.
If you want to create new entry of book.
publisher = Publisher.objects.get(name='Test publisher') author = Author.objects.get(name='Test author') Book.objects.create(title='Title1', publication_date='28/10/2013', authors=author, publisher=publisher)
0👍
Let’s say you want to add a Stephen King’s book Pet Semetary. You need to have the publisher and author instances already before adding the book object. Then it’s very simple:
publisher = Publisher.objects.get(name='Simon & Schuster')
author = Author.objects.get(name='Stephen King')
new_book = Book(title='Pet Semetary',
publication_date='28/10/2013',
authors=author,
publisher=publisher)
new_book.save()
Is this the solution you were looking for?
update on comment
If the book object exists you can just apply it like so:
# create Author and Publisher:
new_author = Author(first_name='Stephen', last_name='King')
new_author.save()
new_publisher = Publisher(...bla bla...)
new_publisher.save()
# link them to your already existing book instance
book_instance = Book.objects.get(title='Pet Semetary')
book_instance.author = new_author
book_instance.publisher = new_publisher
Of course, you should use less general names than new_author or book_instance but you get the idea
👤yuvi
- [Answer]-Djangorestframework:get the value with manytomanyfield
- [Answer]-Django import models.py FK error
- [Answer]-Django models, how to set object owner while saving
- [Answer]-URLS Mixed up with django
Source:stackexchange.com