【问题标题】:What is an effective way to bulk create objects with related objects in django?在 django 中批量创建具有相关对象的对象的有效方法是什么?
【发布时间】:2021-01-25 13:46:58
【问题描述】:

我有以下型号:

class LocationPoint(models.Model):
    latitude = models.DecimalField(max_digits=16, decimal_places=12)
    longitude = models.DecimalField(max_digits=16, decimal_places=12)

    class Meta:
        unique_together = (
            ('latitude', 'longitude',),
        )
class GeoLogEntry(models.Model):
    device = models.ForeignKey(Device, on_delete=models.PROTECT)
    location_point = models.ForeignKey(LocationPoint, on_delete=models.PROTECT)
    recorded_at = models.DateTimeField(db_index=True)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

我有很多传入的记录要创建(一次可能数千个)。

目前我是这样创建它们的:

# Simplified map function contents (removed mapping from dict as it's unrelated to the question topic
points_models = map(lambda point: LocationPoint(latitude=latitude, longitude=longitude), points)

LocationPoint.objects.bulk_create(
     points_models,
     ignore_conflicts=True
)

# Simplified map function contents (removed mapping from dict as it's unrelated to the question topic
geo_log_entries = map(
            lambda log_entry: GeoLogEntry(device=device, location_point=LocationPoint.objects.get(latitude=latitude, longitude=longitude), recorded_at=log_entry.recorded_at),
            log_entries
        )

GeoLogEntry.objects.bulk_create(geo_log_entries, ignore_conflicts=True)

但我认为它不是很有效,因为它运行 N SELECT 查询 N 记录。有没有更好的方法来做到这一点?

我使用 Python 3.9、Django 3.1.2 和 PostgreSQL 12.4。

【问题讨论】:

  • 我假设它是lambda point: LocationPoint(latitude=point.latitude, ...)),所以point.latitde 而不是latitutude
  • 我还可以推荐一种肮脏的解决方案。如果您实际上不需要将创建的对象作为响应返回,请使用 celery 之类的东西异步执行该部分

标签: python django postgresql django-models django-queryset


【解决方案1】:

bulk_create(...) 会将您创建的对象作为列表返回。您可以在 Python 端过滤这些对象,而不是对您的数据库进行查询,因为它们已经被获取。

location_points = LocationPoint.objects.bulk_create(
     points_models,
     ignore_conflicts=True
)

geo_log_entries = map(
    lambda log_entry: GeoLogEntry(
        device=device, 
        location_point=get_location_point(log_entry, location_points),      
        recorded_at=log_entry.recorded_at
    ),
    log_entries
)

GeoLogEntry.objects.bulk_create(geo_log_entries, ignore_conflicts=True)

您需要做的就是实现get_location_point 满足您的需求

【讨论】:

  • 问题是对于大多数数据库来说,它不会在对象中填写主键,这意味着不能使用这些来为location_point赋值。
  • 是的,创建的对象的 PK 为空。
  • @WillemVanOnsem AFAIK 使用 Postgres 12 和 Django 3 足以设置主键。 OP 指定他正在使用 Django 3.1.2 和 PostgreSQL 12.4
  • @artem 嗯,好的。我只是虽然我做过一次......
  • Django docs 表示必须设置主键
【解决方案2】:

主要问题是获取要批量链接到的对象。一旦我们存储了所有这些对象,我们就可以批量获取这些对象:

from django.db.models import Q

points_models = [
    LocationPoint(latitude=point.latitude, longitude=point.longitude)
    for point in points
]

LocationPoint.objects.bulk_create(
     points_models,
     ignore_conflicts=True
)

qfilter = Q(
    *[
          Q(('latitude', point.latitude), ('longitude', point.longitude))
          for point in log_entries
    ],
    _connector=Q.OR
)


data = {
    (lp.longitude, lp.latitude): lp.pk
    for lp in LocationPoint.objects.filter(qfilter)
}

geo_log_entries = [
    GeoLogEntry(
        device=entry.device,
        location_point_id=data[entry.longitude, entry.latitude],
        recorded_at=entry.recorded_at
    )
    for entry in log_entries
]

GeoLogEntry.objects.bulk_create(geo_log_entries, ignore_conflicts=True)

因此,我们批量获取我们需要链接到的所有对象(因此使用一个查询),制作一个映射主键上的经度和纬度的字典,然后将 location_point_id 设置为该点。

但重要的是使用小数,或者至少是一种匹配的类型。浮点是棘手的,因为它们很容易产生舍入误差(因此经度和纬度通常存储为“定点”数字,例如整数为 1 '000 大或 1'000'000 大)。否则,您应该使用与通过查询生成的数据相匹配的算法。

【讨论】:

  • 谢谢!对于 1000 条记录的查询(86 毫秒对 1100 毫秒)来说,这要快得多,但在 Python 方面仍然很慢(4.4 秒对 16 秒)。关于如何优化它的任何提示?
  • @artem:对于字典来说,这不应该那么慢。对于线性搜索,这当然是另一回事。您或许可以尝试分析性能差距的确切位置。
  • 似乎只是调试模板渲染时间(+调试工具栏成本),而创建data的时间成本随着记录数的增长而快速增长(10k在python端创建data需要20秒),但我想我会优化它。再次感谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多