how to write this querySet with Django?
<p>I started learning Django QuerySets but I didn't succeed to write it in this case where I must agregate 2 models related by a foreign key .</p>

<p>I have 2 models <code>user</code> and <code>course</code> where course contains a foreign key of <code>user</code></p>

<pre><code>class user(models.Model):
    first_name = models.CharField(max_length=100)
    middle_name = models.CharField(max_length=100, null=True, blank=True)

class Course(models.Model):
    user= models.ForeignKey(User)
    course_name = models.CharField(max_length=100)
</code></pre>

<p>and I want to translate this <code>sql</code> statement into <code>querysets</code> :</p>

<pre><code>select * from user u, course c 
where u.id = c.user_id
and c.course_name='science' ;
</code></pre>

<p>could someone help me please ?</p>

<p>If what you want is a set of courses with each course instance having a set of related users you do this:</p>

<pre><code>Course.objects.select_related('user').filter(course_name='science')
</code></pre>

<p>Please see: <a href="https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related</a></p>

<blockquote>
  <p>select_related(*fields)   Returns a QuerySet that will âfollowâ
  foreign-key relationships, selecting additional related-object data
  when it executes its query. This is a performance booster which
  results in a single more complex query but means later use of
  foreign-key relationships wonât require database queries.</p>
</blockquote>

<p>If on the other hand you want a list of users and the courses they are following you do</p>

<pre><code>user.objects.filter(course__name='science')
</code></pre>

<p>This is the reverse traversal of a foreign key relationship. Please note that by convention django model names begin with an upper case latter. Your model is 'user' but really ought to be 'User'</p>

python django django-models