我有这个model.py:
class Topping(models.Model):
name = models.CharField(max_length=32)
def __str__(self):
return self.name
class Base(models.Model):
name = models.CharField(max_length=32)
slug = models.SlugField(primary_key=True)
class Advanced(models.Model):
toppings = models.ManyToManyField(Topping)
class Mymodel(Base, Advanced):
...
def toppings_list(self):
list_top = Advanced.toppings
return list_top
我想在我的管理员中显示浇头列表(最好是格式化,因此只列出Topping模型的字段name
的列表),所以:
class MymodelAdmin(admin.ModelAdmin):
#list_display = (..., model.Mymodel.toppings_list(), ...) #Error: missing 1 required positional argument: 'self'
#list_display = (..., model.Mymodel.toppings_list(self), ...) #Error: self is not definited
list_display = (..., model.Mymodel.toppings_list, ...) #Gibberish: <django.db.models.fields.related_descriptors.ManyToManyDescriptor object at 0x0387FFD0>
只有最后一个有效,但没有任何帮助。
我也尝试了这些(我想在显示之前格式化列表):
class MymodelAdmin(admin.ModelAdmin):
mylist=model.Mymodel.toppings_list #I don't change nothing for now
#mylist=[t for t in model.Mymodel.toppings_list] #Error: 'function' object is not iterable
list_display = ('mylist') #core.Topping.None
再一次,最后一个有效,但没有给出任何有用的东西(Topping isn&n = t)
谢谢
答案 0 :(得分:1)
您只需将方法的名称用作字符串。
list_display = ("toppings_list", ...)
但请注意,你的toppings_list方法本身绝对没有意义。您需要返回与当前对象相关的浇头,而不是字段对象,然后您需要将其格式化为字符串。
def toppings_list(self):
return ", ".join(self.toppings.values_list("name", flat=True))