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

753 Views Asked by At

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

2

There are 2 best solutions below

0
willeM_ Van Onsem On BEST ANSWER

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}'
0
Lawrence Bird On

I'm not sure if this exactly the solution you are looking for but you could override the __str__ method of ModelA to return the information in a single line.

So for example:

class ModelA(models.Model):
  first_field = models.CharField(max_length=16)
  second_field = models.CharField(max_length=16)

  def __str__(self):
      return f"{self.first_field} ({self.second_field'})"

Your admin view should then show each object as "foo (bar)"