pythondjangodjango-adminmany-to-manydisplayobject

How can I display all fields from a Many-to-Many Model in Django Admin


I have the following Models:

class ModelA(models.Model):
    some_field_A = models.CharField()
    some_other_field_A = models.CharField()
    
class ModelB(models.Model):
    some_field_B = models.CharField()
    many_to_many_relation = models.ManyToManyField(ModelA)

In admin.py I am using filter_horizontal to edit the ManyToManyField:

class ModelB(admin.ModelAdmin):
    model = ModelB
    filter_horizontal = ('many_to_many_relation',)

but it shows only some_field_A and I want it to show both fields from ModelA, because the entries in ModelA are unique depending on both fields and as you can see from the picture there are multiple entries with the same value (i.e. some_field_A = EUV) but they have different values for some_other_field_A:

enter image description here


Solution

  • It displays the result of the __str__(…) method you defined in your ModelA, so if you return the value of some_field in the __str__(…) method, then it will return only the data of some_field.

    You thus can alter this method and return both fields:

    class ModelA(models.Model):
        some_field_A = models.CharField()
        some_other_field_A = models.CharField()
    
        def __str__(self):
            return f'{self.some_field_A} {self.some_other_field_A}'