我正在使用django 1.8.我在django admin中显示了一个多对多的字段,就像这个例子一样.
class PurchaseOrder(models.Model): product = models.ManyToManyField('Product') vendor = models.ForeignKey('VendorProfile') dollar_amount = models.FloatField(verbose_name='Price') class Product(models.Model): products = models.CharField(max_length=256) def __unicode__(self): return self.products class PurchaseOrderAdmin(admin.ModelAdmin): fields = ['product', 'dollar_amount'] list_display = ('get_products', 'vendor') def get_products(self, obj): return "\n".join([p.products for p in obj.product.all()])
问题是如果我每页显示100行,它会进行100次查询.对于外键,有一个神奇的list_select_related,但你不能在那里放置多对多字段.如何避免重复查询?
---更新:
我试过了:
def get_queryset(self, request): qs = super(PurchaseOrderAdmin, self).get_queryset(request) return qs.prefetch_related('products')
它仍在每行执行重复查询.