1

I just want to know what type of SQL join is happening in the following view. I read about types of SQL joins but I am not able to figure out what is happening here.

class WishListItemsView(ListAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = WishListItemsCreateSerializer

    def get_queryset(self):
        user = self.request.user
        return WishListItems.objects.filter(owner=user)

My models:

class WishListItems(models.Model):
    owner = models.ForeignKey(User, on_delete=models.CASCADE,blank=True)
    #wishlist = models.ForeignKey(WishList,on_delete=models.CASCADE, related_name='wishlistitems')
    item = models.ForeignKey(Product, on_delete=models.CASCADE,blank=True, null=True)
    wish_variants = models.ForeignKey(Variants,on_delete=models.CASCADE, related_name='wishitems')

I can see it in Django debug toolbar, but it is authenticated so I cant see the queries.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Reactoo
  • 916
  • 2
  • 12
  • 40
  • 1
    Well, looking at your code _no_ joins are happening and Django would be making a new query for each of your foreign keys you access. – Abdul Aziz Barkat Jun 06 '21 at 13:19
  • Shouldnt a join happen when we apply a filter in the view?? I am new to this. On what cases join happens then?? – Reactoo Jun 06 '21 at 13:29

1 Answers1

0

No joins are happening in your code. The following line is the queryset you return:

WishListItems.objects.filter(owner=user)

This filtering does not need any joins, Django will simply use the SQL WHERE clause to make this filter. Suppose the primary key of the user here is 1, then the query would be somewhat like:

SELECT <ALL OF YOUR TABLES COLUMNS HERE> FROM "<APP_NAME>_wishlistitems" WHERE "<APP_NAME>_wishlistitems"."owner_id" = 1

You can see the exact query by writing:

print(WishListItems.objects.filter(owner=user).query)

Moving further if you do want to make some join for optimizing or speeding up things use select_related [Django docs] which will make Django use an INNER JOIN:

WishListItems.objects.filter(owner=user).select_related('owner', 'item') # select the related owner and item
Abdul Aziz Barkat
  • 19,475
  • 3
  • 20
  • 33
  • Hello @Abdul can you help me on this?? https://stackoverflow.com/questions/67861083/using-select-related-in-django-view-increases-query-times select_related question – Reactoo Jun 06 '21 at 16:56