I have Django model “AmountOfBooks” that is used just as balance for Book model.
If this is not good pattern for database modeling just say so.
Anyway AmountOfBooks have two fields:
class AmountOfBooks(models.Model): book = models.ForeignKey(Book, editable=False) amount = models.PositiveIntegerField(default=0, editable=False, help_text="Amount of book.")
They are set to editable=False, because this model is meant to be edited only by code.
Eg. when book is created object for that book in AmountOfBooks is set to 0 and when books are added or taken balance is either increased or decreased.
So in this way fields for AmountOfBooks model are not shown when I click on”Add Amount of books” button in Django admin.
But I want to remove that button from Django admin just for AmountOfBooks model.
How to do it ?
Continuation of this question is available on How to make Django model just view (read-only) in Django Admin?
It is easy, just overload has_add_permission method in your Admin class like so:
class MyAdmin(admin.ModelAdmin): def has_add_permission(self, request): return False
To do it you need to override
has_add_permission method in your Admin class:
class AmountOfBooksAdmin(admin.ModelAdmin): def has_add_permission(self, request): return False # to disable editing for specific or all fields # you can use readonly_fields attribute # (to see data you need to remove editable=False from fields in model): readonly_fields = ('book', 'amount')
You asked about your design itself so I’ll address this first. If you want to keep an history of your stock then having a distinct table (model) makes sense but then you’d need a timestamp field and a unique constraint on (book, timestamp). Now if you just want to keep the stock current the relationship between book and amount is really one to one so the amount field really belongs to the book table. In this case you just have to add “amount” to the book’s ModelAdmin “readonly_fields” attribute and your problem is solved.