Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango QuerySets: Get unique/first element from ForeignKey field
    text
    copied!<p>I've following models:</p> <pre><code>class SchoolClass(models.Model): title = models.CharField() max_students = models.IntegerField(default=10) is_published = models.BooleanField(default=False) class Session(models.Model): school_class = models.ForeignKey(SchoolClass, related_name="sessions") start_date = models.DateField() enrolled_students = models.IntegerField() </code></pre> <p>A SchoolClass can have multiple Sessions (e.g. "Maths for Dummies" on Monday, Tuesday and Friday = 3 Sessions).</p> <p>On my Index page (ListView), I'd like to show all upcoming classes (which have at least one session) only once, since classes which have a lot of sessions would make the overview messy.</p> <p>How can I create a list of Session-Objects (I can get the relevant course info via session.school_class), which comply with following requirements:</p> <ul> <li><code>start_date__gte=datetime.now().date()</code></li> <li><code>school_class.is_published=True</code></li> <li>it's the first elelement of SchoolClass (<code>oder_by('start_date')[0]</code>)</li> </ul> <p>Thanks!</p> <p>PS: I'm running MySQL as DB, so distinct('field') won't work..</p> <hr> <p><strong>Edit:</strong></p> <p>Below is my current solution, which works, but is not very clean (redundant hits on the DB)</p> <pre><code>def get_sessions_mixin(filter_args): session_qs = [] qs = SchoolClass.objects.filter(**filter_args) for schoolclass in qs: session_qs.append(schoolclass.get_first_session()) #session_qs = Session.objects.filter(course_meta__is_deleted=False, date_from__gte=datetime.now().date()).\ # annotate(Max('date_from')) #session_qs = qs.order_by('get_first_session__date_from') return session_qs </code></pre> <p>and inside models.py</p> <pre><code>class Sessions(models.Model): # ... def get_first_session(self): if self.is_published: tmp_sessions = self.sessions.filter(date_from__gte=datetime.now().date()) if tmp_sessions: return tmp_sessions.order_by('date_from')[0] return None </code></pre>
 

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