2024-06-28 15:27:53 发布
网友
假设我有以下模型定义:
class Topping(models.Model): name = models.CharField(max_length=40) class Pizza(models.Model): toppings = models.ManyToManyField(Topping)
现在让我们假设我想在管理站点注册模型,使用内联模型管理员允许在编辑比萨时添加配料:
这导致了一个相当突出的问题:
正如你所见,这个标签很难看。有没有定制的方法?在
为关系定义模型类的一种更快更脏的方法是重新定义__str__或{}方法:
__str__
class ToppingInline(admin.TabularInline): ... Pizza.toppings.through.__str__ = lambda self: 'Topping'
You would control what displays for an object using the ^{} or ^{} 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)
为关系定义模型类的一种更快更脏的方法是重新定义}方法:
__str__
或{You would control what displays for an object using the ^{} or ^{} method.
You could manage the many to many yourself要定义此属性,请执行以下操作:
相关问题 更多 >
编程相关推荐