I have a problem with extra sql requests when work with api.
My models:
class Book(models.Model):
...
authors = models.ForeignKey(Authors, on_delete=models.CASCADE,related_name='book', null=True, blank=True)
...
class Authors(models.Model):
author= models.ForeignKey(AuthorTable, on_delete=models.CASCADE,related_name='authors_author', null=True, blank=True)
artist= models.ForeignKey(AuthorTable, on_delete=models.CASCADE,related_name='authors_artist', null=True, blank=True)
class AuthorTable(models.Model):
name=models.CharField(max_length=200, null=True, blank=True)
photo = models.ImageField(upload_to='authors/', blank=True)
My serializers
class AuthorTableSerializer(serializers.ModelSerializer):
class Meta:
model = AuthorTable
fields = ['name','photo']
class AuthorsSerializer(serializers.ModelSerializer):
author=AuthorTableSerializer()
artist=AuthorTableSerializer()
class Meta:
model = Authors
fields = ['author','artist']
class BookSerializer(serializers.ModelSerializer):
authors=AuthorsSerializer()
...
class Meta:
model = Book
fields = ['authors',...]
and view
class BookList(viewsets.ModelViewSet):
permission_classes = (permissions.IsAdminUser,)
queryset = Book.objects.select_related('authors'...)
serializer_class = BookSerializer
My problem is that when I get an API request for a book, I also get a double sql query for the AuthorTable model, and while I can set Book.objects.select_related(‘authros’), I can’t set Book.objects.select_related( 'autortable)
In other words. I don’t know how to attach a external model to the book’s query that is not directly related to it.