gpt4 book ai didi

python - 列表显示django中的多对多

转载 作者:IT老高 更新时间:2023-10-28 21:40:25 26 4
gpt4 key购买 nike

class Product(models.Model):
products = models.CharField(max_length=256)

def __unicode__(self):
return self.products

class PurchaseOrder(models.Model):
product = models.ManyToManyField('Product')
vendor = models.ForeignKey('VendorProfile')
dollar_amount = models.FloatField(verbose_name='Price')

我有那个代码。不幸的是,错误出现在带有 ManyToManyField

的 admin.py 中
class PurchaseOrderAdmin(admin.ModelAdmin):
fields = ['product', 'dollar_amount']
list_display = ('product', 'vendor')

错误提示:

'PurchaseOrderAdmin.list_display[0]', 'product' is a ManyToManyFieldwhich is not supported.

但是,当我从 list_display 中取出 'product' 时,它会编译。那么如何在 list_display 中显示 'product' 而不会出错?

edit:也许更好的问题是如何在 list_display 中显示 ManyToManyField

最佳答案

您可能无法直接执行此操作。 From the documentation of 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()])

或者定义一个模型方法,并使用它

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')

关于python - 列表显示django中的多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18108521/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com