S
S
Salavat Sharapov2014-11-03 10:48:23
Django
Salavat Sharapov, 2014-11-03 10:48:23

How to make custom list_display in django admin?

Good morning!
For example, there are models:
models.py

class Library(models.Model):
    title = models.CharField()
    cover = models.ImageField()
    description = models.TextField()

class Book(models.Model):
    material = models.ForeignKey(Library)
    user = models.ForeignKey(User)

How to display a separate Book column in the admin panel in the listing of the Library model?
I understand that something like this is needed:
admin.py
class LibraryAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'get_book', )
    model = Library

    def __init__(self, *args, **kwargs):
        super(LibraryAdmin, self).__init__(*args, **kwargs)
        self.list_display_links = ('id', 'get_book')

And in the Library model, how, more precisely, how to implement feedback ??.
models.py.Library
class Library(models.Model):
    title = models.CharField()
    cover = models.ImageField()
    description = models.TextField()

    def get_book(self):
        if self.book: # Как тут осуществить обратную связь?
            return self.book
        else:
           return None
    get_book.short_description = "Книга"

class Book(models.Model):
    material = models.ForeignKey(Library)
    user = models.ForeignKey(User)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anatoly Scherbakov, 2014-11-03
@Altaisoft

In my opinion, you can have more than one Book instance correspond to one Library instance ? Why then is it written "book" and not "books"? Every Library instance has a book_set property that contains a list of all the books that match the given object. You can rename it by specifying related_name :
Now you can list books like this:

class LibraryAdmin(admin.ModelAdmin):
    list_display = ('id', 'title', 'book_list', )

    def book_list(self, obj):
        return ', '.join(book.name for book in self.books)

Or do you have one library corresponds to only one book, and vice versa?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question