简体   繁体   中英

Displaying the value of ManyToMany relationship in django admin

I am trying to display a brand of a bike in my django admin panel. I have managed to display the title, but I am struggling with the brand.

Here's my models.py:

class Bike(models.Model):
  item = models.OneToOneField(Item, on_delete=models.CASCADE)
  category = models.ManyToManyField(Category, blank=True)
  image = models.ImageField(upload_to='bikes')
  brand = models.ManyToManyField(Brand, null=True)

  def __str__(self):
      return self.item.title

class Brand(models.Model):
  name = models.CharField(max_length=20)

  def __str__(self):
      return self.name

I have tried that:

def __str__(self):
  return self.brand.name

But nothing is displaying then. Any ideas how to display the self.item.title and brand name at the same time?

Try this instead and see if it works.

`def brand_names(self):
        return ', '.join([x.name for x in self.brand.all()])`

You need to return brand name in str So I give you stuff apply that

def ___str__(self):
    return ",".join([brand.name for brand in self.brand.objects.all()])

Above stuff give all the brand name in your admin panel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM