简体   繁体   English

在django admin中显示ManyToMany关系的值

[英]Displaying the value of ManyToMany relationship in django admin

I am trying to display a brand of a bike in my django admin panel.我试图在我的 django 管理面板中显示一个自行车品牌。 I have managed to display the title, but I am struggling with the brand.我已设法显示标题,但我正在为品牌而苦苦挣扎。

Here's my models.py:这是我的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?任何想法如何同时显示 self.item.title 和品牌名称?

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你需要在 str 中返回品牌名称 所以我给你的东西适用

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以上内容在您的管理面板中提供了所有品牌名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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