-1

I am calculating size of the item by multiplying two fields.

Size = order_size_weight x requested_selling_price

I have two approches to do that.

1. Model Property

return float(self.order_size_weight) * float(self.requested_selling_price)

2. Modify QuerySet

return self.extra(
                select={"priority": "COALESCE(bm_rank, sales_rank, id)",
        "size": "order_size_weight*requested_selling_price",  # for oder_by size.

})

Problem

When i use the second approach, i can not use Annotate to aggregate or take sum of all the Sizes.

Question

  1. What is the best / Fast approach to calculate Size
  2. Can i use Annotate after using extra select

EDIT

Solution of 2.

I am able to solve the second problem by Using select extra before using annotate will help solve the problem.

A.J.
  • 6,664
  • 10
  • 55
  • 74
  • [Here](http://stackoverflow.com/q/4567543/821594) is a related question – stalk Sep 11 '14 at 07:32
  • 1
    I suggest you edit the title to match the question better - now it is quite generic and does not hint of the any facts which might be relevant: COALESCE, select extra, etc.. – Mikko Ohtamaa Sep 11 '14 at 09:13
  • did you just down voted for the title? I have updated it though. – A.J. Sep 11 '14 at 09:17

1 Answers1

0

While it should still be possible to do both annotate and aggregate for calculated fields, it's not recommended in terms of database performance if you also want to sort on it (and don't have an index for the calculated result).

For cases like these I would recommend the usage of enter link description here (or something similar). You can use a callback function to store the results in the database: http://initcrash.github.io/django-denorm/tutorial.html#creating-denormalized-fields-using-callback-functions

class SomeModel(models.Model):
    order_size_weight = models.IntegerField()
    requested_selling_price = models.IntegerField()

    @denormalized(models.IntegerField)
    def calculate_size(self):
        return float(self.order_size_weight) * float(self.requested_selling_price)
Wolph
  • 69,888
  • 9
  • 125
  • 143