我有一辆Offer型车,它有一个前键,可以连接到另一辆Category型车.通过这个Category模型,我得到了与这个Category关联的Brand,并将其传递到管理页面上的Offer.但当我在Offer admin page的Dropdown Filter中使用这个Brand字段时,它会生成大量查询.

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,但我只是不知道使用它的确切方法.

推荐答案

似乎没有一种框架支持的干净利落的方式来做到这一点.但在某种程度上,有is个方法.

您将需要细分为RelatedOnlyDropdownFilter,而不是def field_choices.大概是这样的:

class CategoryRelatedOnlyDropdownFilter(RelatedOnlyDropdownFilter):
    def field_choices(self, field, request, model_admin):
        return [("", "---------")] + [
            (category.pk, str(category))
            for category
            in Category.objects.select_related("brand")
        ]
    

Python-3.x相关问答推荐

在Python中从mySQL获取多行

如何使用python将pdf文件的页面合并为单个垂直组合页面

Python webdrivermanager 和 Chrome 115.0 的 URL https://chromedriver.storage.googleapis.com/LATEST_RELEASE_115.0.5790 错误没有此类驱动程序

SQL Server 2022和Python3.10脚本错误

使用 python 查找标记的元素

多进程:两个进程,一起杀死

将两列合并为一列,将它们制成字典 - pandas - groupby

使用 selenium 加速网页抓取

使用 from re findall 组合连续匹配并分离非连续匹配

正则表达式:匹配字符串中的分隔符(字母和特殊字符)以形成新的子字符串

魔术8球txt文件列表

排队多个子进程

python用户输入5个偶数并打印最大的

Await Future 来自 Executor:Future 不能在await表达式中使用

获取比较多列的最大值并返回特定值

使用 distutils 分发预编译的 python 扩展模块

如何通过命令行将数组传递给python

如何将numpy数组图像转换为字节?

在 ubuntu 20.04 中安装 libpq-dev 时出现问题

无法解码 Python Web 请求