当模型中有外键时,导出很慢,当我排除外来没有问题时,它开始快速下载。这可能是什么问题?谢谢!
我的代码就像,
resources.py
class InvoiceResource(resources.ModelResource):
class Meta:
model = Invoices
views.py
def export_invoice(request):
person_resource = InvoiceResource()
dataset = person_resource.export()
response = HttpResponse(dataset.xlsx, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="invoices.xlsx"'
return response
models.py
class Invoices(models.Model):
store_code = models.ForeignKey(MasterData, on_delete=models.CASCADE, db_column='Store Code', blank=True, null=True, verbose_name='Store Code')
erp_id = models.CharField(db_column='ERP ID', max_length=200, blank=True, null=True, verbose_name='ERP ID')
store_name = models.CharField(db_column='Store Name', max_length=200, blank=True, null=True, verbose_name='Store Name')
答案 0 :(得分:0)
我认为你应该使用select_related
class ModelA(models.Model):
fk = models.Foreingkey(ModelB)
class ModelB(models.Model):
title = models.CharField(max_lenght=20)
如果您使用:
a_objects = ModelA.objects.all()
for obj in a_objects:
fk = obj.fk
每个对象都需要查询数据库
但是如果你使用
a_objects = ModelA.objects.all().select_related('fk')
for obj in a_objects:
fk = obj.fk
在这种情况下只对数据库进行一次查询。
有关更多信息,请转到https://docs.djangoproject.com/en/2.0/ref/models/querysets/
class InvoiceResource(resources.ModelResource):
def get_queryset(self):
return super().get_queryset().select_related('store_code')
class Meta:
model = Invoices