Django-ORM 而不是 python for 循环
Django-ORM instead of python for loop
大家好!
这么简单的问题,有时我曾经用 python for 循环遍历我的模型,这对网站的性能不利。
我有3个3型号:
class A(models.Model):
Bs = ManyToManyField(B)
class B(models.Model):
Cs = ManyToManyField(C)
class C(models.Model):
name = CharField(max_length=100)
如果我想让 C 模型的所有实例与 A 的实例相关,我将如何进行而不是这个python for 循环?
all_c = []
for b in a_instance.Bs.all():
for c in b.Cs.all():
all_c.append(c)
你可以使用 prefetch_related
https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-related
all_c = []
for b in a_instance.Bs.all().prefetch_related('Cs'):
for c in b.Cs.all():
all_c.append(c)
但更好的方法是只过滤 C
模型
all_c = C.objects.filter(b_set__a_set__in=[a_instance])
# or if you need it to be list and not queryset
all_c = list(C.objects.filter(b_set__a_set__in=[a_instance]))
大家好!
这么简单的问题,有时我曾经用 python for 循环遍历我的模型,这对网站的性能不利。
我有3个3型号:
class A(models.Model):
Bs = ManyToManyField(B)
class B(models.Model):
Cs = ManyToManyField(C)
class C(models.Model):
name = CharField(max_length=100)
如果我想让 C 模型的所有实例与 A 的实例相关,我将如何进行而不是这个python for 循环?
all_c = []
for b in a_instance.Bs.all():
for c in b.Cs.all():
all_c.append(c)
你可以使用 prefetch_related
https://docs.djangoproject.com/en/2.0/ref/models/querysets/#prefetch-related
all_c = []
for b in a_instance.Bs.all().prefetch_related('Cs'):
for c in b.Cs.all():
all_c.append(c)
但更好的方法是只过滤 C
模型
all_c = C.objects.filter(b_set__a_set__in=[a_instance])
# or if you need it to be list and not queryset
all_c = list(C.objects.filter(b_set__a_set__in=[a_instance]))