在django admin显示中缓存反向外键对象

时间:2017-07-27 07:47:20

标签: foreign-keys django-admin django-queryset

我试图从反向外键对象中获取一些不同的属性,并在django admin list_display上显示它。但是这个当前的方法会多次调用db查询

models.py:
class Author(models.Model):
    name = models.CharField()
    ...
    def get_all_book(self):
        return self.book_set.all()

class Book(models.Model):
    author = models.ForeignKey(Author)
    aaa = some field type
    bbb = some field type
    ...

admin.py:
class AuthorAdmin(admin.ModelAdmin):
    def book_aaa(obj):
        booklist = obj.get_all_book
        all_bookaaa = ",".join([k.aaa for k in booklist])
        return all_bookaaa
    def book_bbb(obj):
        booklist = obj.get_all_book
        all_bookbbb = ",".join([k.bbb for k in booklist])
        return all_bookbbb
    list_display = ('name', book_aaa, book_bbb)

admin.site.register(Author, AuthorAdmin)

因为我需要在单独的列中分隔这些书信息,但是如果使用这种方法,它可能会调用" book_set.all()" queryset两次,这对性能非常不利。有没有正确的方法来实现这个问题?

1 个答案:

答案 0 :(得分:0)

通过为对象创建额外属性,并检查属性是否存在。

def get_booklist(self, obj):
    if not hasattr(obj, 'booklist')
        obj.booklist = obj.get_all_book
    return obj
def book_aaa(self, obj):
    booklist = self.get_booklist(obj).booklist
    all_bookaaa = ",".join([k.aaa for k in booklist])
    return all_bookaaa
def book_bbb(self, obj):
    booklist = self.get_booklist(obj).booklist
    all_bookbbb = ",".join([k.bbb for k in booklist])
    return all_bookbbb
list_display = ('name', 'book_aaa', 'book_bbb')

也许这不是最好的解决方案,但至少可以防止多次调用查询集。