在django admin中显示来自另一个模型的字段

pdkcd3nj  于 2023-07-01  发布在  Go
关注(0)|答案(2)|浏览(188)

假设我有两个模型。
我想使程序模型中的主题字段出现在UserProgramAdmin中。
最好的办法是什么?

class Program(models.Model):
    name = models.CharField(max_length=15, blank=False)
    summary = models.CharField(max_length=200, blank=True)
    subject = models.ManyToManyField(Subject, related_name='all_subjects')
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True, editable=False)
    updated_at = models.DateTimeField(auto_now=True, editable=False)

    def __str__(self) -> str:
        return self.name

class UserProgram(models.Model):
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    program = models.ForeignKey(
        Program,
        on_delete=models.CASCADE,
    )
    is_active = models.BooleanField(default=True)
    is_finish = models.BooleanField(default=False, editable=False)

/admin.py
class UserProgramAdmin(admin.ModelAdmin):
    list_display = ('user', 'program' , 'is_active', 'is_finish')
hs1ihplo

hs1ihplo1#

您应该在UserProgram上定义一个方法,然后在UserProgramAdmin list_display属性中调用它
models.py

class UserProgram(models.Model):
    #...model attributes
    
    def get_subject(self):
        subject = self.program.subject.all()
        return subject

admin.py

class UserProjectAdmin(admin.ModelAdmin):
    list_display = ('get_subject', 'attribute_to_display')
vqlkdk9b

vqlkdk9b2#

最好的方法是在__str__ in Program字段中显示subject,如下所示:

class Program(models.Model):
    #Your other code
    def __str__(self):
        return f'{self.name} - {self.subject}'

然后Program的主题显示在UserProgram的admin中。

相关问题