如何在内联模型管理中自定义为ManyToManyField显示的标签?

时间:2016-02-28 01:21:11

标签: python django django-admin

假设我有以下模型定义:

.Parse()

现在让我们假设我想在管理站点注册模型,使用内联模型管理员允许在编辑比萨饼时添加浇头:

class Topping(models.Model):
    name = models.CharField(max_length=40)

class Pizza(models.Model):
    toppings = models.ManyToManyField(Topping)

这导致了一个相当明显的问题:

ValueType

如您所见,标签很难看。有没有办法定制它?

2 个答案:

答案 0 :(得分:1)

You would control what displays for an object using the __str__ or __unicode__ method.

You could manage the many to many yourself定义此属性,如下所示:

...

class Pizza(models.Model):
    toppings = models.ManyToManyField(Topping, through="PizzaToppingRelationship")


class PizzaToppingRelationship(models.Model):
    pizza = models.ForeignKey(Pizza)
    topping = models.ForeignKey(Topping)

    def __str__(self):
        return 'Pizza Topping - {}'.format(self.topping.name)

答案 1 :(得分:1)

为关系定义模型类的更快更脏的方法是重新定义__str____unicode__方法:

class ToppingInline(admin.TabularInline):
    ...
    Pizza.toppings.through.__str__ = lambda self: 'Topping'