Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to return most popular items in a table, but where each item is unique?
    primarykey
    data
    text
    <p>I am trying to figure out a tricky Django query that I hope you can help with. I have this model:</p> <pre><code>class ActiveVenue(models.Model): event = models.ForeignKey(Event) venue = models.ForeignKey(Venue) class Venue(models.Model): name = models.CharField(max_length=200) class Event(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=200) </code></pre> <p>In my app there are many Events and each event can have multiple active venues, hence my current data structure. I would prefer if your solution is not "change your model to foo" as this is already a deployed site and I would like to keep the current model structure.</p> <p>I want to write a query that returns the most popular venues but in which a venue is only counted once for each user. As an example, if I have one user with four events and they use the same venue every time, I only want to count that venue once when determining the most popular venues.</p> <p>To illustrate this, imagine this is my data:</p> <pre><code>event: A user: bob venue: The Hill event: B user: bob venue: The Hill event: C user: bob venue: The Hill event: D user: jane venue: The Oaks event: E user: sarah venue: The Pound event: F user: david venue: The Pound event: G user: ron venue: The Oaks event: H user: erica venue: The Oaks </code></pre> <p>Here the popular order would be:</p> <pre><code>1. The Oaks 2. The Pound 3. The Hill </code></pre> <p>Any suggestions how I write a query to do this that works on both postgres and sqlite (in other words, doesn't rely on <code>distinct()</code> (not supported in sqlite))?</p> <p>Thanks!</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