Answer the question
In order to leave comments, you need to log in
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)
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')
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
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)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question