I have a library with shelves and books. I point each book to one shelf in a one-to-many relationship. If a book is pointing to a Null
it means that it's in the library, but not in the shelf yet.
#models.py
class Shelf(models.Model):
pass
class Book(models.Model):
shelf = models.ForeignKey(Shelf, blank=True, null=True)
Then:
#admin.py
class BookInLine(admin.TabularInLine):
model = Book
extra = 0
class Shelf(admin.ModelAdmin):
inlines = [ BookInLine, ]
When I edit the Shelf I can see and modify all the books that are in that shelf.
Problem:
- I have a lot of books already in the library (pointing to
Null
). - If I click 'Add another Book' from the inline it will create a totally new book. But I want to avoid that. I would like to select from the books that are already in the library but doesn't belong to any shelf yet.
Hi the following code worked for me:
It creates an admin view where you will se the normal Shelf stuff and the additional inline which is a raw id field and you have the posssibility to add new relations and you can chose from existing objects with the "magnifier" icon, which results in a pop-up of a list of all existing books. Besides chose one Book in the pop-up you can also create new Books there. So from my understanding this solves all your requirements
a better solution for this problem is explained here: one-to-many inline select with django admin
edited for your use-case: