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