简体   繁体   中英

Search_field for a definition in Django

In 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

in admin.py:

search_fields = ['total_price'] will work. however, I can not search for get_total_price. So how can I make it so that search can pick up definitions. Or how can I make it so that the object total_price gets and saves the value of the return on get_total_price?

You should override the save() method and insert total_price on add and update. It's easier and better for performance.

Not tested:

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)

I've found you this snippet . It's quite old so it could need some changes to make it work with recent django versions.

You can see usage instructions in the panel to the right.

Note that it's implemented for direct fields values. You'll have to make some tweaks to make it work with the sum.

Also, this project seems to cover a similar requirement though it is a very early version.

Note : Don't call sum with the queryset. You should use

from django.db.models import Sum

self.product.all().aggregate(Sum('price_for_each_item'))

to get the value straight from the BD.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM