Djangoの汎用関係を照会する方法
-
21-12-2019 - |
質問
私は活動をしていますが、N + 1のクエリの回避方法を理解することはできません。
基本的に、チームや場所にはフォロワー/アクティビティがあり、各ユーザーは彼らが従うチーム/場所から引っ張られた活動フィードを持っているフォロワーです。
私のモデルからのスニペット:
class Follower(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Activity(models.Model):
...
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Team(models.Model):
...
followers = GenericRelation('Follower')
activities = GenericRelation('Activity')
class Place(models.Model):
...
followers = GenericRelation('Follower')
activities = GenericRelation('Activity')
.
私はDRFを使って活動のための基本的なシリアライザを持っています、私はトリッキーな部分がビューの中にあると思います:
class ActivityViewSet(viewsets.ModelViewSet):
def list(self, request):
#N+1 query
activities = [f.content_object.activities.all() for f in request.user.follower_set.all()]
...
.
だからこれは機能しますが、そのクエリをやるためのより良い方法はありますか?
解決
def list(self, request):
items = {}
for f in request.user.follower_set.all():
items.setdefault(f.content_type_id, []).append(f.object_id)
activities = Activity.objects.get_empty_queryset() # get_empty_query_set in <1.5
for k, v in items.iteritems():
activities |= Activity.objects.filter(content_type=k, object_id__in=v)
.
これは2つのクエリまで沸騰します。Follower
とActivity
が同じオブジェクト(チームまたは場所)に関連している場合、content_type
とobject_id
は同じです。ちょっとしたPythonの処理、およびTADAは、現在のユーザーに関連するすべてのアクティビティが2つのクエリで関連付けられています。
所属していません StackOverflow