[英]Search_field for a definition in Django
在models.py中
class PurchaseOrder(models.Model):
product = models.ManyToManyField('Product', null =True)
total_price= models.FloatField()
def get_total_price(self):
return sum([p.price_for_each_item for p in self.product.all()]) #this just returns a float such as 42323
在admin.py中:
search_fields = ['total_price']
将起作用。 但是,我无法搜索get_total_price。 因此,我该如何做,以便搜索可以选择定义。 或者如何使对象total_price获取并保存get_total_price上的返回值?
您应该重写save()
方法,并在添加和更新时插入total_price。 它更容易实现更好的性能。
未经测试:
class PurchaseOrder(models.Model):
product = models.ManyToManyField('Product', null =True)
total_price= models.FloatField()
def save(self, *args, **kwargs):
self.total_price = sum([p.price_for_each_item for p in self.product.all()])
super(PurchaseOrder, self).save(*args, **kwargs)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.