Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show a field name instead of the whole object for ManyToMany object in django admin site

My models are as follows:

class Retailer(BaseModel):
    brand = models.ManyToManyField('brands.Brand',blank=True)

class Brand(BaseModel):
    name = models.CharField(max_length=100, unique=True)
    website = models.URLField(max_length=500, blank=True, default='')

And my admin class is as follows:

class RetailerAdmin(admin.ModelAdmin):
    filter_horizontal = ('brand',)

The admin site does show the multi-select field for me, but every entry in the brand list is just shown as Brand object, which makes no sense to me. I want every entry to be shown as the name field of that brand. What should I do?

like image 788
chaonextdoor Avatar asked Apr 10 '14 22:04

chaonextdoor


1 Answers

You can just add __unicode__ (python 2) or __str__ (python 3) method to your model so it'll look like this

class Brand(BaseModel):
    name = models.CharField(max_length=100, unique=True)
    website = models.URLField(max_length=500, blank=True, default='')

    def __unicode__(self):
        return self.name
like image 113
Alexander Larikov Avatar answered Sep 23 '22 06:09

Alexander Larikov