如何在管理面板中自定义多方内联的“描述”

时间:2019-08-29 10:59:19

标签: django django-admin

我有那些非常简单的模型:

class Activity(BaseModel):
    name = models.CharField(max_length=200, blank=True, null=True)

class Person(BaseModel):
    activities = models.ManyToManyField('Activity', related_name='persons')

admin.py中,我为此做了一个内联,它的工作原理如下:

class PersonActivitiesInlineAdmin(admin.StackedInline):
    model = Profession.persons.through
    fk_name = 'person'

class PersonAdmin(admin.ModelAdmin):
    inlines = (PersonActivitiesInlineAdmin, )

我的问题是,在管理界面中描述内联的字符串就像

 Profession: Person_activities object (831)
 Profession: Person_activities object (832)
 Profession: Person_activities object (835)
 Profession: Person_activities object (838)

那么如何在管理面板中自定义多方内联的“描述”?

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案是使用throughPersonActivity的多对多关系显式创建联接模型,并为其添加描述:

class Activity(BaseModel):
    name = models.CharField(max_length=200, blank=True, null=True)

class Person(BaseModel):
    activities = models.ManyToManyField(
        Activity,
        related_name='persons',
        through='PersonActivity'  # Use PersonActivity for join model
    )

class PersonActivity(BaseModel):
    description = models.CharField(max_length=255)  # Your custom description field
    activity = models.ForeignKey(Activity, on_delete=models.CASCADE)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)

    def __str__(self):
        # The admin automatically renders the string representation of the model
        # e.g. Person_activities object (838)

        # Thus you can return your custom description in order to display it
        return self.description