0

I have a situation where I am not sure whether I would be using select_related or not. I have a model like this:

class Example(models.Model): 

    title = models.CharField(max_length=255, blank=True)  
    message = models.TextField(blank=True)
    user = models.ForeignKey(
    User,
    on_delete=models.CASCADE,
    null=True,
    related_name="user_example",
)
    /................./

Now in my view I have use filtering logic like this:

def get_queryset(self):
    
    search = self.request.query_params.get("search", None)

    if search_query is not None:
        queryset = Reactions.objects.filter(
            Q(user__name__icontains=search)
            | Q(user__email__icontains=search)                
        ).distinct()

Here Example model has a fk relation with User, so its a forward relation not a reverse relation. Should I be appeding .select_related('user').filter(...) in this above example to reduce the no of queries or there is no need here...I can't figure it out.

Serizalizer:

class ExampleSerializer(serializers.ModelSerializer):

    user = UserSerializer()

    class Meta:
        model = Reactions
        fields = ["id", "user", "title", "message"]
Reactoo
  • 916
  • 2
  • 12
  • 40
  • Can you share the serializer you are using? If you are accessing the related user in your serializer then yes you should use select_related, if not then it is not necessary – Iain Shelvington Jan 18 '22 at 17:34
  • hello @IainShelvington i Have updated it with the serializer. please check. – Reactoo Jan 18 '22 at 17:53

1 Answers1

0

Yes, you should. From docs:

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python...

In your case we deal with a ForeignKey, so select_related is suitable. If you want to make sure that this decreases a number of DB queries, you can install django-debug-toolbar for that.

Yevgeniy Kosmak
  • 3,561
  • 2
  • 10
  • 26
  • I have django-toolbar, but i am using postman for api calls because authentication is required for that api call. Now how can i use debug-toolbar in this case?? – Reactoo Jan 19 '22 at 07:13
  • @Reactoo [`django-debug-toolbar-request-history`](https://github.com/djsutho/django-debug-toolbar-request-history) has to help you. You can temporarily disable the authentication if you are not sure if it hinders you. – Yevgeniy Kosmak Jan 19 '22 at 10:37