I am using drf and django-debug-toolbar.
# model
class Item(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
owner = models.ForeignKey(User, on_delete=models.CASCADE)
# serializer
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = ["id", "title", "description", "owner"]
view
class ItemViewSet(ModelViewSet): queryset = Item.objects.all()
serializer_class = ItemSerializer
And I noticed this extra query that gets generated and I don’t know why.
SELECT "marketplace_user"."id",
"marketplace_user"."password",
"marketplace_user"."last_login",
"marketplace_user"."is_superuser",
"marketplace_user"."first_name",
"marketplace_user"."last_name",
"marketplace_user"."is_staff",
"marketplace_user"."is_active",
"marketplace_user"."date_joined",
"marketplace_user"."email"
FROM "marketplace_user"
LIMIT 1000
Can someone help me to figure this out?
1
Use .select_related(…)
[Django-doc] to fetch the data of the owner
in the same query:
class ItemViewSet(ModelViewSet):
queryset = Item.objects.select_related('owner')
serializer_class = ItemSerializer
If it is however the form that Django generates when you visit the HTML form, then this is to populate the dropdown, this is not part of the API logic itself.
That looks like it isn’t supposed to happen.
- Are you using signals in relation to the
Item
model? - Or do you have
depth=1
on the serializer? - Or does your view (or serializer) call
item.owner
in any way?
All of those would explain why that extra query is generated.
The LIMIT 1000
clause is added by djangorestframework
, where 1000 items is the default setting when fetching data across related fields.
3