你好,大家好!!
这是一个简单的问题,有时我会用python循环循环遍历我的模型,这对网站的性能不好。
我有三种型号:
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循环?
all_c = []
for b in a_instance.Bs.all():
for c in b.Cs.all():
all_c.append(c)发布于 2018-06-02 05:45:04
你可以用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]))https://stackoverflow.com/questions/50652520
复制相似问题