For example, I have following models:
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
class SNS(models.Model):
name = models.CharField(max_length=255)
# for display in raw_id_fields
def __str__(self):
return self.name
class PersonSNS(models.Model):
person = models.ForeignKey('Person', related_name='sns')
sns = models.ForeignKey('SNS')
url = models.CharField(max_length=255)
And in admin.py
class PersonSNSInline(admin.StackedInline):
model = PersonSNS
fields = ('sns', 'url')
raw_id_fields = ('sns',)
@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
inlines = [PersonSNSInline]
def get_queryset(self, request):
return super(PersonAdmin, self).get_queryset(request).prefetch_related('sns')
However, django-debug-toolbar shows the executed SQL like:
SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` IN (1, 2, 3, 5, 6)
and
SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 1
Duplicated 5 times.
SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 5
Duplicated 5 times.
SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 6
Duplicated 5 times.
SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 3
Duplicated 5 times.
SELECT `sns`.`id`, `sns`.`name` FROM `sns` WHERE `sns`.`id` = 2
Duplicated 5 times.
I'm wondering why the PersonSNSInline still query the database one by one though I have prefetch the related data.