Building a django queryset over foreign key and onetoone
<p>I have some two models (in different apps/models.py files) related with User:</p>

<pre><code>class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False)
    ...


class CourseStudent(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    semester = models.ForeignKey(Semester)
    ...
</code></pre>

<p>I am trying to get a queryset of all profiles that have at least one course in the current semester.</p>

<p>How can I generate a queryset of profiles, where <code>profile.user</code> has at least one <code>CourseStudent</code> instance, and filtered so that <code>coursestudent.semester=current_semester</code>?  </p>

<p>Since a student may have multiple courses in the semester, the duplicates also need to be removed (unique profiles only in the queryset)</p>

<p>EDIT:  I am using postgresql and trying to figure out if I need to use <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#distinct" rel="nofollow">distinct with an argument</a>.</p>

<p>Not tested. Maybe you should try</p>

<pre><code>class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False)
    ...


class CourseStudent(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="course_student")
    semester = models.ForeignKey(Semester)

Profile.objects.filter("what_you_want").exclude(user__courser_student=None).distinct()
</code></pre>

python django postgresql foreign-keys django-queryset