Django list_display在反向模型中不起作用

amrnrhlw  于 2022-11-18  发布在  Go
关注(0)|答案(1)|浏览(148)

Django list_display不支持反向模型,我想list_display显示两个独立但相关的表的标题和制作公司。
这是我的网站model.py

class ProjectBaseModel(models.Model):
title = models.CharField("Titel", max_length=100, blank=False, unique=True)
former_title = models.CharField("ehemaliger Titel", max_length=100, blank=True)
title_international = models.CharField(
    "Titel, international", max_length=100, blank=True, null=True, unique=True
)
program_length = models.PositiveSmallIntegerField(
    verbose_name="Länge in Min.", blank=True, validators=[MaxValueValidator(300)]
)
   
def __str__(self):
    return self.title

class Meta:
    abstract = True
    ordering = ["title"]

class FeatureFilm(ProjectBaseModel):
    class Meta:
        verbose_name = "Kinofilm"
        verbose_name_plural = "Kinofilme"

class ProjectCompanySet(models.Model):
featurefilm = models.ForeignKey(
    FeatureFilm, on_delete=models.CASCADE, null=True, blank=True
)
tv_movie = models.ForeignKey(
    TvMovie, on_delete=models.CASCADE, null=True, blank=True
)

production_company = models.ForeignKey(
    CompanyOrBranch,
    related_name="production_company",
    verbose_name="Produktionsfirma",
    on_delete=models.SET_NULL,
    blank=True,
    null=True,
)

我的***FeatureFilm***表继承自***ProjectBaseModel***表。我想在django后台管理中显示***FeatureFilm***列表。在列表中我想显示相应的名称,但我也想显示字段production_company,它是ProductionCompanySet表的一行,该表是与FeatureFilm表相关的子表。production_company字段是指向CompanyOrBranch表的外键。
您可以在此处看到此表:

class CompanyOrBranch(CompanyBaseModel):
name = models.CharField(
    "Firma oder Niederlassung",
    max_length=60,
    blank=False,
)

这是我的admin.py

from django.contrib import admin
from .models import (
   FeatureFilm,
   TvMovie,
   ProjectCompanySet,
   Vendor,
   StaffList,
   VendorVFX,
   QuoteAndEffort,
)

class ProjectCompanySetInLine(admin.StackedInline):
model = ProjectCompanySet
fields = (
    "production_company",
    "co_production",
    "distributor",
    "broadcast",
    "world_sales",
)
classes = ["collapse"]
extra = 0

class FeatureFilmAdmin(admin.ModelAdmin):
inlines = [
    QuoteAndEffortSetInLine,
    ProjectCompanySetInLine,
    VendorVFXSetInLine,
    VendorSetInLine,
    StaffListSetInLine,
]
list_display = ["title", "projectcompanyset__production_company", ]
ergxz8rk

ergxz8rk1#

我的问题不够精确。是的,FeatureFilm表通过外键指向ProjectCompanySet表。它有一个字段:production_company。我实际上想要的是第一个ProjectCompanySet条目,以及从中显示的第一个公司。与此同时,我所管理的是ProjectCompany的str函数显示给我。但是,如果我有多个ProjectCompanySet表,那么也会显示几次。但是,我只想要第一个!,然后还有production_company的字符串。我还没有管理。这是我到目前为止的扩展代码:

class FeatureFilmAdmin(admin.ModelAdmin):
inlines = [
    QuoteAndEffortSetInLine,
    ProjectCompanySetInLine,
    VendorVFXSetInLine,
    VendorSetInLine,
    StaffListSetInLine,
]
list_display = ["title", "program_length", "get_company_set"]

def get_company_set(self, Featurefilm):
    return FeatureFilm.objects.filter(pk=Featurefilm.id).values(
        "projectcompanyset__production_company__name"
    )

相关问题