在Django管理中显示ManyToMany关系的值 [英] Displaying the value of ManyToMany relationship in django admin

查看:45
本文介绍了在Django管理中显示ManyToMany关系的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在django管理面板中显示一个自行车品牌.我设法显示了标题,但是我在与品牌斗争.

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.

这是我的模型.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

我尝试过:

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

但是什么也没显示.有什么想法可以同时显示self.item.title和品牌名称吗?

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()])`

这篇关于在Django管理中显示ManyToMany关系的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆