我有两个模型,我需要从一个表(模型)获取数据到另一个表,我的逻辑工作但需要一段时间(大约5分钟)这是因为Times Table有大约90,000条数据线。我将首先发布我的两个模型,然后是我用来关联的逻辑,以及我从Times表中获得的内容:
模型1:
class otreport(models.Model):
sales_order_shipset = models.CharField(max_length=30)
wms = models.CharField(max_length=50)
status = models.CharField(max_length=200)
aging = models.DateField(null=True, blank=True)
carrier = models.DateField(null=True, blank=True)
add_date = models.DateTimeField(null=True, blank=True)
asn_validation = models.DateTimeField(null=True, blank=True)
docs_add_date = models.DateTimeField(null=True, blank=True)
po_number = models.CharField(max_length=20, unique=True)
模型2:
class Times(models.Model):
external_order = models.CharField(max_length=20)
planning_order = models.CharField(max_length=20)
wms_order = models.CharField(max_length=40)
customer_id = models.CharField(max_length=50)
service_level = models.CharField(max_length=100)
state = models.CharField(max_length=5)
status_date = models.DateTimeField(null=True, blank=True)
order_date = models.DateTimeField(null=True, blank=True)
order_add_date = models.DateTimeField(null=True, blank=True)
asn_sent_time = models.DateTimeField(null=True, blank=True)
docs_received_time = models.DateTimeField(null=True, blank=True)
docs_processing_time = models.CharField(max_length=100)
这是我的逻辑,它发生了什么(为了更快地使用列表来重新阅读销售po_numbers)并将外部订单与销售订单联系起来以获取我想要的信息:
def import_times(request):
print "Import data from Times to OT"
po_cache = list()
for item in otreport.objects.all():
if item.po_number in po_cache:
continue
times = Times.objects.filter(external_order=item.sales_order_shipset)
for wi in times:
po_cache.append(wi.external_order)
item.wms = wi.wms_order
item.status = wi.shipment_status
item.aging = wi.status_date
item.carrier = wi.service_level
item.add_date = wi.order_add_date
item.asn_validation = wi.asn_sent_time
item.docs_add_date = wi.docs_received_time
item.save()
我的问题是,如果有人有更好的想法来运行这个更有效率,如果你需要更多的数据o细节随时问:),
感谢您的时间
答案 0 :(得分:1)
你可以尝试两件事
可能是一个小改进但不使用缓存列表,而是使用集合。查找会更快。
批量保存。
试试这个:
from django.db import transaction
def import_times(request):
transaction.set_autocommit(False)
print "Import data from Times to OT"
po_cache = set()
for item in otreport.objects.all():
if item.po_number in po_cache:
continue
times = Times.objects.filter(external_order=item.sales_order_shipset)
records_count = 0
for wi in times:
records_count += 1
po_cache.add(wi.external_order)
item.wms = wi.wms_order
item.status = wi.shipment_status
item.aging = wi.status_date
item.carrier = wi.service_level
item.add_date = wi.order_add_date
item.asn_validation = wi.asn_sent_time
item.docs_add_date = wi.docs_received_time
item.save()
if records_count >= 10000:
transaction.commit()
records_count = 0
transaction.commit()