Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass queryset data to another query django

I have the following model. I am trying to select all from UserClasses where a specific class_id is specified. I then want to get the User data for each of the results

class UserClasses(models.Model):
    class_id = models.ForeignKey(Class)
    user = models.ForeignKey(User)

This is my django view where I am trying to pull all User objects:

users = UserClasses.objects.filter(class_id=data['class_id'])
user_details = User.objects.filter(#get users.id from userclasses and compare here)

How can I pass the results from one queryset into another?

like image 442
Sam Munroe Avatar asked Sep 14 '25 06:09

Sam Munroe


1 Answers

You can use the __in operator combined with the values_list() method of Django to achieve what you want.

users = UserClasses.objects.filter(class_id=data['class_id'])
user_details = User.objects.filter(id__in=users.values_list('id', flat=True))
like image 200
gallen Avatar answered Sep 16 '25 19:09

gallen