Django admin. Change display string of ManyToManyField over __str__

Hi!

I have model which looks like this.

class Toy(models.Model):
    name = models.CharField()
    serial_number = models.IntegerField()
    ...

    def __str__(self):
        return self.name

class Sales(models.Model):
    user = models.OneToOneField('auth.User', )
    toys = models.ManyToManyField(Toy, ...)
...
...

/admin.py

class SalesAdmin(admin.ModelAdmin):
    fields = ['user', 'toys']

And I added this model to django admin.
The problem is I need to show serial numbers of toys instead of names for this SalesAdmin.
And I do not want to change __str__ method of Toy model since name is more useful in other parts of django admin.
How can I change display string only for this specific admin?
Thanks in advance

You need to show the toy serial number when adding a new sale?

The first “solution” I can think of is overriding the ModelAdmin form.

In addition to @marcorichetta’s answer above, also take a look at the ModelMultipleChoiceField, particularly the to_field_name attribute.

1 Like

Shouldn’t be looking at label_from_instance method?

As I understand, he wants to change the M2M field description.

class CustomToysChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return f"{obj.name} - {obj.serial_number}"

Yep, good catch, thanks!

This looks like what I wanted.
Thanks @marcorichetta