当Entry对象数大于5000时,django有没有办法更有效地执行以下操作?如何在django中有效地使用_set.all()?
models.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
需要花费几秒钟时间查看我的所有条目。有没有更好的办法?
你可以去周围的其他方式。获取所有Color对象,并通过'entry'对它们进行排序,然后进行迭代。 – AKS
您可以根据[我刚刚提出的另一个问题的答案]使用'prefetch_related'(http://stackoverflow.com/a/35893764/1324033) – Sayse
要扩展@Sayse评论,'selected_related'也可以作为选项。 https://docs.djangoproject.com/en/1.9/ref/models/querysets/#select-related你基本上想做一个急切的加载。 – themanatuf