我有一个模型
Offer
,它有另一个模型 Category
的 ForeginKey。通过这个 Category
模型,我得到与此 Brand
关联的 Category
并将其传递到管理页面上的 Offer
。但当我在 Brand
上的下拉过滤器中使用此 Offer admin page
字段时,它会生成大量查询。
models.py
class Brand(BaseFields):
name = models.CharField()
...
def __str__(self):
return self.name()
class Category(BaseFields):
name = models.CharField()
brand = models.ForeignKey(
Brand,
on_delete=models.SET_NULL,
null=True,
blank=True,
)
parents = models.ManyToManyField(
'self',
blank=True,
verbose_name='Parent_category',
related_name='children',
symmetrical=False
)
def __str__(self):
return str(self.brand) + '----' + self.name
class Offer(BaseFields):
name = models.CharField()
category = models.ForeignKey(
Category,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='offer',
verbose_name='Related_category'
)
def __str__(self):
return self.name
admin.py
class OfferAdmin(admin.ModelAdmin):
list_select_related = True
list_display = (
'name',
'brand_name',
'category',
'place',
'status'
)
list_editable = ('place', 'status')
list_filter = (
('category__brand', RelatedOnlyDropdownFilter),
('category', RelatedOnlyDropdownFilter),
'status'
)
fields = [
'name',
'description',
'tech_info',
'ctru',
'category',
'place',
'status'
]
autocomplete_fields = ['category']
actions_on_bottom = True
list_per_page = 25
search_fields = ['name']
def get_queryset(self, request):
return super().get_queryset(request).select_related('category', 'category__brand')
@admin.display(description='Brand', ordering='name')
def brand_name(self, obj):
return obj.category.brand.name
据我了解,这两个块是主要问题
def __str__(self):
return str(self.brand) + '----' + self.name
list_filter = (
('category__brand', RelatedOnlyDropdownFilter),
('category', RelatedOnlyDropdownFilter),
'status'
)
我需要通过计算所有报价的
Brand
来减少生成的查询量。我确实知道我必须在某个地方使用 select_related
但我只是不知道使用它的确切方法。
你很幸运! Django admim 站点有一个
get_queryset(...)
方法,您可以在 ModelAdmin
子类中重写该方法:
https://docs.djangoproject.com/en/5.0/ref/contrib/admin/
class YourModelAdmin(admin.ModelAdmin):
def get_queryset(self, request):
return super().get_queryset(request).select_related(...)