列表中的多对多显示django [英] many-to-many in list display django
问题描述
class PurchaseOrder(models.Model):
product = models.ManyToManyField('Product')
vendor = models.ForeignKey('VendorProfile')
dollar_amount = models.FloatField(verbose_name='Price')
class Product(models.Model):
products = models.CharField(max_length=256)
def __unicode__(self):
return self.products
I有那个代码不幸的是,admin.py中的错误出现在ManyToManyField
I have that code. Unfortunately, the error comes in admin.py with the "ManyToManyField"
class PurchaseOrderAdmin(admin.ModelAdmin):
fields = ['product', 'dollar_amount']
list_display = ('product', 'vendor')
错误说'PurchaseOrderAdmin.list_display [0]','product'是一个ManyToManyField不受支持。
The error says "'PurchaseOrderAdmin.list_display[0]', 'product' is a ManyToManyField which is not supported."
然而,它编译时我从list_display中取出product。那么如何在list_display中显示product而不给出错误?
However, it compiles when I take 'product' out of list_display. So how can I display 'product' in list_display without giving it errors?
编辑:可能更好的问题是如何在list_display中显示ManyToManyField?
edit: Maybe a better question would be how do you display a ManyToManyField in list_display?
推荐答案
您可能无法直接执行。 从<$ c $的文档c> list_display
You may not be able to do it directly. From the documentation of list_display
ManyToManyField字段不受支持,因为这将需要
为表中的每一行执行单独的SQL语句。如果
想要这样做,请给您的模型一个自定义的方法,并将该方法的名称添加到
到list_display。 (见下文关于list_display中的自定义
方法的更多信息。)
ManyToManyField fields aren’t supported, because that would entail executing a separate SQL statement for each row in the table. If you want to do this nonetheless, give your model a custom method, and add that method’s name to list_display. (See below for more on custom methods in list_display.)
您可以这样做:
class PurchaseOrderAdmin(admin.ModelAdmin):
fields = ['product', 'dollar_amount']
list_display = ('get_products', 'vendor')
def get_products(self, obj):
return "\n".join([p.products for p in obj.product.all()])
或定义一个模型方法,并使用
OR define a model method, and use that
class PurchaseOrder(models.Model):
product = models.ManyToManyField('Product')
vendor = models.ForeignKey('VendorProfile')
dollar_amount = models.FloatField(verbose_name='Price')
def get_products(self):
return "\n".join([p.products for p in self.product.all()])
和在管理员 list_display
list_display = ('get_products', 'vendor')
这篇关于列表中的多对多显示django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!