Reactoo
Reactoo

Reputation: 1042

use of select_related in this case of django rest?

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"]

Upvotes: 0

Views: 864

Answers (1)

Yevhenii Kosmak
Yevhenii Kosmak

Reputation: 3860

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.

Upvotes: 0

Related Questions