当 Entry 对象的数量大于 5000 个条目时,django 中有没有一种方法可以更有效地执行以下操作?
模型.py
class Entry(models.Model):
user = models.TextField(db_column='User', blank=True)
date = models.DateTimeField(blank=True)
class Color(models.Model):
color = models.TextField(blank=True)
entry = models.ForeignKey(Entry)
假设我想获得每个条目的所有颜色...
entrys = Entry.objects.all()
for e in entrys:
print e.color_set.all()
我希望能够将每个对象与特定条目相关联。例如,在这样的 csv 表中。
user, color
john, blue
john, orange
bob, green
bob, red
bob, purple
浏览我的所有条目需要几秒钟。有没有更好的办法?
最佳答案
你应该使用 prefetch_related
entrys = Entry.objects.all().prefetch_related('color_set')
for e in entrys:
print e.color_set.all()
它将执行 2 个查询,而不是执行 n 个查询,一个用于条目,一个用于外键查找
关于python - 如何在 Django 中有效地使用 _set.all()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35894498/