Django:list_display ManyToManyField 排序
落叶无声
阅读:46
2025-02-15 21:57:57
评论:0
我有以下代码:
#models.py
class Repair(models.Model):
products = models.ManyToManyField(Product)
description = models.TextField()
def products_list(self):
return ', '.join([a.name for a in self.products.all()])
class Product(models.Model):
name = models.CharField(max_length=50,blank=False)
description = models.TextField(blank=True)
#admin.py
class RepairAdmin(admin.ModelAdmin):
list_display = ('products_list', 'description')
正如您所看到的,我使用带有连接的自定义模型字段来显示 ModelAdmin list_display 属性上的所有修复相关产品,这是正确工作的。
现在我的问题是:如何在 list_display 上使自定义字段排序?我只想按 ManyToMany relashiontship 上的第一项排序。我尝试在模型上使用以下代码:
products_list.admin_order_field = 'products__name'
包括这一行,我可以激活字段排序,但它无法正常工作......当请求字段排序时,它会在表上显示与它具有的关系一样多的记录重复。
我一直在研究,我发现的最接近解决方案的是:
Django admin: how to sort by one of the custom list_display fields that has no database field
但我没有看到将其应用于我的案例的正确方法。
请您参考如下方法:
您会看到“表上的重复记录与其所具有的关系一样多”,因为 'products__name'
正在获取所有 Product
s 与 Repair
相关.
如果您想按多对多关系中的第一项排序 products
在您的 ModelAdmin 中,那么制作 property
可能是最容易的。获得第一个产品——然后将它分配给 admin_order_field
:
class Repair(models.Model):
products = models.ManyToManyField(Product)
description = models.TextField()
def products_list(self):
return ', '.join([a.name for a in self.products.all()])
# add a property which gets the name of the first product
@property
def first_product(self):
self.products.all().first() # first() was added in 1.6, otherwise use [0]
class RepairAdmin(admin.ModelAdmin):
list_display = ('products_list', 'description')
# use that property to only get the first product when ordering
products_list.admin_order_field = 'first_product__name'
声明
1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。