[Fixed]-How to do complex join in Django

1👍

One try would be to first get all of the user1s and user2s from the first relation

u1 = Feature1.objects.all().values_list('user1', flat=True)
u2 = Feature1.objects.all().values_list('user2', flat=True)

and then get the Feature2 objects from the second relation that match those users

queryset = Feature2.objects.filter(user1__in=u1, user2__in=u2).order_by('-percentage')

I’d like to also offer an alternative to your database design that I feel will help you query your models more efficiently. Why not change Feature2 so that it has a ForeignKey to Feature1 like so

class Feature2(models.Model):
    feature1 = models.ForeignKey(Feature1, verbose_name="Feature 1")

    ...

Then you could join the two this way

queryset = Feature2.objects.filter(feature1__in=Feature1.objects.filter(u1=self.request.user)).order_by('-percentage')

Leave a comment