How to show GenericRelation object field value in list_display?

models.py

class ModelA(models.Model):
  name = models.CharField(max_length=40)

class ModelB(models.Model):
  name = models.CharField(max_length=100)
  model_c = GenericRelation("modelc")

class ModelC(models.Model):
  model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE)
  content_type = models.ForeignKey(ContentType, 
    limit_choices_to={"model__in":["modelb", "modelx", "modely"]}, 
    on_delete=models.CASCADE)
  object_id = models.PositiveIntegerField()
  details = GenericForeignKey("content_type","object_id")

admin.py

class AdminModelB(admin.ModelAdmin):
  list_display = ("name", "model_a")

  @staticmethod
  def model_a(obj):
    return obj.model_c.model_a  # 'GenericRelatedObjectManager' object has no attribute 'model_a'

I have ModelB having GenericRelation in field model_c where ModelC contain ContentType as ForeignKey. Now I want to display ModelA.name in list_display of ModelB. I have tried like other foreignkey fields but it gives me an error 'GenericRelatedObjectManager' object has no attribute 'model_a'.

Back to Top