[Answered ]-Django queryset: All Model1 objects where a Model2 exists with a model1 AND the given user

2👍

✅

You can go through Model2:

Model2.objects.filter(model1=model1, user=user) \
.values_list(‘model1’, flat=True) \
.distinct()

First you filter out all Model2’s with user as their user and then create a list of distinct Model1’s.

list(set([m2.model1 for m2 in Model2.objects.filter(user=user).all()]))

In your specific example:

list(set([m2.model1 for m2 in Model2.objects.filter(user_id=1).all()]))

UPDATE

Try this too:

Model1.objects.filter(model2__user=user)

Leave a comment