You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Admin:筛选FeatureFilm关联的指定角色制片公司

问题解决:在FeatureFilm Admin列表页显示首个制片公司

需求回顾

已关联FeatureFilm与CompanyInvolved模型,需在Admin列表页筛选出company_role为"Produktion"的记录,并仅展示首个制片公司。


解决方案

1. 核心修改:Admin中的字段展示方法

直接修改FeatureFilmAdmin中的get_company_involved方法,添加过滤条件并处理空值:

@admin.register(FeatureFilm)
class FeatureFilmAdmin(admin.ModelAdmin):
    inlines = [
        SalesInfoSetInLine,
        ContentInfoSetInLine,
        CompanyInvolvedSetInLine,
    ]

    list_display = [
        "title",
        "get_company_involved",   
        "program_length_planned",
    ]

    def get_company_involved(self, obj):
        # 过滤出角色为Produktion的关联记录,取第一条
        production_entry = obj.companyinvolved_set.filter(company_role="Produktion").first()
        # 处理空值,避免报错
        if production_entry and production_entry.company_involved:
            return production_entry.company_involved.name
        return "无"  # 无匹配时显示占位符

    get_company_involved.short_description = "Produktion"

2. 性能优化(针对大数据量场景)

如果Admin列表页数据较多,为避免N+1查询问题,可通过Prefetch预取指定条件的关联数据:

from django.db.models import Prefetch

@admin.register(FeatureFilm)
class FeatureFilmAdmin(admin.ModelAdmin):
    # ... 其他配置不变 ...

    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        # 预取仅包含Produktion角色的CompanyInvolved记录
        queryset = queryset.prefetch_related(
            Prefetch(
                'companyinvolved_set',
                queryset=CompanyInvolved.objects.filter(company_role="Produktion"),
                to_attr='production_companies'
            )
        )
        return queryset

    def get_company_involved(self, obj):
        # 从预取的集合中取第一条
        if hasattr(obj, 'production_companies') and obj.production_companies:
            first_prod = obj.production_companies[0]
            return first_prod.company_involved.name if first_prod.company_involved else "无"
        return "无"

关键说明

  • 利用反向关联obj.companyinvolved_set直接访问关联记录,比重新查询FeatureFilm表更高效
  • 明确添加company_role="Produktion"过滤条件,精准获取制片公司
  • 增加空值判断,避免因无匹配记录或关联公司为空导致的页面报错
  • 预取优化能将多次查询合并为一次,大幅提升列表页加载速度

内容的提问来源于stack exchange,提问作者gomez_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:51:56