Here is a related manager I wrote:
class PortfolioItemManager(models.Manager):
use_for_related_fields = True
def extended(self):
return self.extra(select = {'current_price':'current_price', 'current_value':'current_price*quantity', 'gain':'current_price*quantity - cost'},
tables = ['pm_core_contract', ],
where = ['pm_core_contract.id = pm_core_portfolioitem.contract_id', ]
)
Here are the results that stumps me:
In [10]: PortfolioItem.objects.extended()
Out[10]: []
In [11]: PortfolioItem.objects.extended().count()
Out[11]: 402
Result from count() is correct. What am I missing here?
EDIT: The generated SQL is correct and can be executed against the db directly.
EDIT2: The issue stems from the last 2 select arguments, which feature arithmetic operations.
I think I have just figured out the problem. Thanks go to Alex, whose comment has sparked the idea:
The PortfolioItem model has the properties
current_valueandcurrent_gain, which I have been trying to replace with calculated SQL fields. It was my mistake to name one of the extra() method’s select fields ‘current_value’ without removing the property, as that led to the model having two fields with the same name. When I did away with that overlapping, everything became OK. Lesson is learned.