Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango "extra" query
    primarykey
    data
    text
    <p>I have the following model structure in my models.py, with Items and Offers:</p> <pre><code>class Item(models.Model): STATUS_CHOICES = ( ('A', 'Active'), ('C', 'Cancelled'), ) status = models.CharField(max_length=11, choices=STATUS_CHOICES) target_amount = models.PositiveIntegerField() ... class Offer(models.Model) STATUS_CHOICES = ( ('A', 'Active'), ('C', 'Cancelled'), ) status = models.CharField(max_length=11, choices=STATUS_CHOICES) amount = models.PositiveIntegerField() item = models.ForeignKey(Item) ... </code></pre> <p>I want to write a query in my views.py to get the following for each Item:</p> <ol> <li>The total of the current (active) offers for this item</li> <li>The percentage of the target that has been met by offers for this item (i.e. [the total from (1)]/target_amount * 100)</li> </ol> <p>I have been trying to achieve this with "extra" as follows (using postgres):</p> <pre><code>items = Item.objects.filter(status='A').extra( select={ 'total_amount' : 'select coalesce(sum(amount),0) from myapp_offer where myapp_offer.item_id = myapp_item.id and myapp_offer.status = \'A\'', 'percentage_met' : '(((select coalesce(sum(amount),0) from myapp_offer where myapp_offer.item_id = myapp_item.id and myapp_offer.status = \'A\') / target_amount) * 100)' } ) </code></pre> <p>Now the first select (<code>total_amount</code>) is working correctly and returns what I expect, but the <code>percentage_met</code> is always 0. Can anyone help me out as to why?</p> <p>Edit: Should have mentioned that I want to be able to order_by the percentage_met</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload