Django access same attribute on different model dynamically
I have different models which has following format.
class Company(models.Model):
pass
class ModelA(models.Model):
company = models.ForeignKey(Company, models.CASCADE)
class ModelB(models.Model):
company = models.ForeignKey(Company, models.CASCADE)
class ModelC(models.Model):
modelb = models.ForeginKey(ModelC)
I want to write generic display field by the use of mixin in django admin for ModelA, ModelC as:
class FieldMixin:
@display(description='field')
def my_field(self, obj):
# normal solution would be this
if object is ModelA and object.company.is_active:
return 'active'
if object is ModelC and object.modelb.company.is_active
return 'active'
# i wanted something like this instead of above. It will be easier if object has immediate attribute but object can have same field in nested object as well.
object._meta.get_fields('company').is_active