Django QuerySet Expression Order

Possible duplicate:
django - ordering a request by computed field

How can I use order_by, for example order_by ('field1' * 'field2') For example, I have products with a price listed in different currencies, so for ordering items I have to do currency conversion.

class Currency(models.Model): code = models.CharField(max_length=3, primary_key=True) rateToUSD = models.DecimalField(max_digits=20,decimal_places=10) class Item(models.Model): priceRT = models.DecimalField(max_digits=15, decimal_places=2, default=0) cur = models.ForeignKey(Currency) 

I would like to have something like:

 Item.objects.all().order_by(F('priceRT')*F('cur__rateToUSD')) 

But, unfortunately, this does not work, I also can not with the annotate. How can I order a QuerySet order by multiplying two model fields.

+4
source share
2 answers

Use the extra() method. In particular, the select argument to specify the equation and the order_by argument to order.

+4
source

The boring way: add an extra field to the Item class called priceUSD and fill it out using the save method. means that you have no load on performing calculations for each request - only for each update. Is this so good or will it not depend on whether you want to write more or read more (given your question, maybe he reads?)

something like that:

 class Item(models.Model): priceRT = models.DecimalField(max_digits=15, decimal_places=2, default=0) cur = models.ForeignKey(Currency) priceUSD = models.DecimalField(max_digits=15, decimal_places=2, default=0) def save(self,*args,**kwargs) self.priceUSD = self.priceRT * self.cur.rateToUSD super(Model,self).save(*args,**kwargs) 

In my django material, when I tried to implement smart computed fields without storing them in the database, I usually found that it has too many flaws to use usefult (for example, it cannot query them, sorting by them). therefore, saving the correct field in the database using a special save method is how I usually did it, and it works fine. you will need a little more error checking, etc.

+2
source

Source: https://habr.com/ru/post/1311174/


All Articles