【问题标题】:Get data from one model to another Django/Python从一个模型获取数据到另一个 Django/Python
【发布时间】:2017-05-05 22:56:05
【问题描述】:

我正在使用 python 和 Django 构建一个应用程序。我有几个模型,但我需要从一个模型获取数据到另一个模型(可以使用 SOSS(销售订单号)建立关系。我确实有这样做的逻辑,但没有我想要的效率。它处理数据大约需要 5-6 分钟。

我的 Model 1 有关系号(po_number),和 Model 2 有关联(这里叫planning_number),因为 Model 2 大概有 93,000 条数据线,所以需要很多时间。

这是我的逻辑:

def import_withtimes(request):
    print "importando With Times a ots report"
    po_cache = list()
    for item in Model1.objects.all():

        if item.po_number in po_cache:
            continue

        withtimes = Model2.objects.filter(planning_order=item.po_number)
        for wi in withtimes:
            po_cache.append(wi.planning_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()

我的问题是:有没有更有效的方法将数据从一个模型反映到另一个模型?

【问题讨论】:

  • 您好,您的代码是要按常规运行还是手动运行?

标签: python django for-loop django-models append


【解决方案1】:

您的model1model2 是否通过models.ForeignKey 字段相关(关联po_numberplanning_order)?然后,您可以使用 QuerySet 来获取相关对象。

您使用的是什么后端数据存储?它是否有相关字段的索引?查看在模型定义 (https://docs.djangoproject.com/en/1.8/ref/models/fields/#db-index) 中的相关字段上设置 db_index=True 选项。

另见Improving performance of django DB query

【讨论】:

  • 它们与外键无关,我应该将它们声明为唯一键吗?它会改善关系吗?
  • Model1和Model2之间是1:1还是1:many的关系?
  • 我正在使用 Mysql 顺便说一句
  • 在这里你可以看到 withtimes = Model2.objects.filter(planning_order=item.po_number) 计划数是两个模型之间的 1:1 关系,一旦犯规我从模型中获取数据2 到模型 1。
  • 你想让我分享我的模型吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多