Note that there are some explanatory texts on larger screens.

plurals
  1. POincremental count and calculation in django model
    primarykey
    data
    text
    <p>Let's say my models are like this:</p> <pre><code>class Publisher(models.Model): name = models.CharField(max_length=30) code = models.SmallIntegerField(unique=True) class Book(models.Model): date = models.DateField(auto_now_add=True) publisher = models.ForeignKey(Publisher) hardback = models.BooleanField() large_print = models.BooleanField() </code></pre> <p>For a given date range, I want to be able to output a CSV which has total number of books per publisher, and percentage of each boolean field.</p> <p>Eg:</p> <pre><code>Publisher-code Total %hardback %large_print: 123 120 32 10 </code></pre> <p>etc</p> <p>(a) So far I'm working on a view that generates a queryset with the total number of books per publisher</p> <pre><code>totalset = Publisher.objects.all() d1 = dict(totalset.annotate(total_books=Count('publisher')).values_list('code','total_books')) </code></pre> <p>Then gets a dictionary-converted queryset of each boolean field e.g.</p> <pre><code>d2 = dict(totalset.filter(book__hardback=True).annotate(hardc=Count('book__hardback')).values_list('code','hardc')) </code></pre> <p>Then get a new dictionary that calculates the percentages based on the intersection of the two sets</p> <pre><code>d3 = {k: round(float(d2[k])*100/d1[k]) for k in d1.viewkeys() &amp; d2.viewkeys()} </code></pre> <p>I'm new to all this, so I feel that this is incredibly convoluted. Is there a more straightforward way ??!</p> <p>(b) If it's possible to do this in the database (e.g. with some sort of model property), is this more efficient than doing it in python as the database gets large ?</p> <p>Thanks very much</p>
    singulars
    1. This table or related slice is empty.
    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