Home > database >  Display field from another model in django admin
Display field from another model in django admin

Time:04-02

Let say I have two model. I want to make subject field in Program model appear in UserProgramAdmin. What is the best way to do that?

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')

Thanks in advance

CodePudding user response:

The best way to do this would be to also show subject in the __str__ in Program field like this:

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

Then the subject of Program shows up in the admin of UserProgram.

CodePudding user response:

You should define a method on UserProgram and then call it in your UserProgramAdmin list_display attribute

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')
  • Related