[Answered ]-How to write this querySet with Django?

2👍

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

Course.objects.select_related('user').filter(course_name='science')

Please see: https://docs.djangoproject.com/en/1.10/ref/models/querysets/#select-related

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.

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

user.objects.filter(course__name='science')

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’

👤e4c5

Leave a comment