Skip to content

Instantly share code, notes, and snippets.

@lu911
Last active October 13, 2022 10:50
Show Gist options
  • Save lu911/692e8edc4d55f7054f72039bf5250e32 to your computer and use it in GitHub Desktop.
Save lu911/692e8edc4d55f7054f72039bf5250e32 to your computer and use it in GitHub Desktop.
django-prefetch_related
# -*- coding: utf-8 -*-
from django.db import models
class Person(models.Model):
name = models.CharField(max_length=128)
class Group(models.Model):
name = models.CharField(max_length=128)
members = models.ManyToManyField(Person, through='Membership')
class Membership(models.Model):
person = models.ForeignKey(Person, on_delete=models.CASCADE)
group = models.ForeignKey("Group", on_delete=models.CASCADE)
date_joined = models.DateField()
invite_reason = models.CharField(max_length=64)
"""
Shell
In [13]: gs = list(Group.objects.all().prefetch_related('members'))
SELECT `app_group`.`id`,
`app_group`.`name`
FROM `app_group`
Execution time: 0.006087s [Database: default]
SELECT (`app_membership`.`group_id`) AS `_prefetch_related_val_group_id`,
`app_person`.`id`,
`app_person`.`name`,
`app_person`.`company_id`
FROM `app_person`
INNER JOIN `app_membership`
ON (`app_person`.`id` = `app_membership`.`person_id`)
WHERE `app_membership`.`group_id` IN (1, 2)
Execution time: 0.006120s [Database: default]
In [14]: gs
Out[14]: [<Group: Group object (1)>, <Group: Group object (2)>]
In [15]: g = gs[0]
In [16]: g.members
Out[16]: <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager at 0x109742520>
In [17]: g.members.all()
Out[17]: <QuerySet [<Person: Person object (5)>, <Person: Person object (6)>]>
"""
@gghotted
Copy link

@YukSeungChan
감사합니다!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment