João Vilaça João Vilaça - 1 year ago 58
Python Question

How do I add several books to the bookstore in the admin form

In django, imagine i have a model bookstore and a model book which has a foreign key to bookStore model . On the django admin,I added like 10 books, and on the bookstore I want to assign multiple books to this one bookstore. How do I do this ? Because even with foreignKey, while editing the bookstore, i can only choose one book...

class BookStore(models.Model):
name = models.CharField(max_length=100)

class Book(models.Model):
name = models.CharField(max_length=100)
store = models.ForeignKey(BookStore, null=True)

Answer Source

Your relationship is the wrong way around. If your bookstore has a fk to a book, you are saying that "each bookstore can only store one single book". Instead, you should have a fk from the book to the book store. This is saying "a book belongs to a bookstore (and only one bookstore)"

class Book:
    bookstore = models.ForeignKey("Bookstore")

class Bookstore:

You need to use an inline form if you want to add multiple books while editing your bookstore object:

class BookInline(admin.StackedInline):
    model = Book

class BookstoreAdmin(admin.ModelAdmin): 
    model = Bookstore
    inlines = [BookInline,]