Search code examples
djangomodeladmin

ModelAdmin, foreign key relation chain


I wonder if it is possible in a clean way to print a foreignkey chain in ModelAdmin:

Image we have this structure:

class Ma(models.Model):
      fa = models.EmailField()

class Mb(models.Model):
      fb = models.ForeignKey('Ma')

class Mc(models.Model):
      name = models.CharField(max_length=50)
      fc = models.ForeignKey('Mb')

Now with ModelAdmin:

Edit: (This is not valid)

class McAdmin(admin.ModelAdmin):
     list_display = ('name', 'fc__fb__fa',)

Or how can I solve this?


Solution

  • See this answer:

    You can create a method on your McAdmin class that returns these nested Foreign Key values:

    class McAdmin(admin.modelAdmin):
        list_display = ('name', 'get_email_foreign_foreign_key')
    
        def get_email_foreign_foreign_key(self, obj):
            return '%s' % obj.fc.fb.fa