Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在django中使用相关对象批量创建对象的有效方法是什么?_Python_Django_Postgresql_Django Models_Django Queryset - Fatal编程技术网

Python 在django中使用相关对象批量创建对象的有效方法是什么?

Python 在django中使用相关对象批量创建对象的有效方法是什么?,python,django,postgresql,django-models,django-queryset,Python,Django,Postgresql,Django Models,Django Queryset,我有以下型号: 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'

我有以下型号:

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',),
        )
我有很多要创建的传入记录(可能一次创建数千条)

目前我创建它们的方式如下:

# 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。

bulk\u 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\u location\u point
满足您的需求

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

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)
从django.db.models导入Q
点数\u模型=[
位置点(纬度=点。纬度,经度=点。经度)
点对点
]
LocationPoint.objects.bulk\u创建(
点(单位)模型,,
忽略冲突=真
)
qfilter=Q(
*[
Q((‘纬度’,点。纬度),(‘经度’,点。经度))
对于日志中的点\u条目
],
_连接器=Q或
)
数据={
(lp.经度,lp.纬度):lp.pk
对于LocationPoint.objects.filter(qfilter)中的lp
}
地理日志条目=[
地志条目(
device=entry.device,
位置\点\ id=数据[entry.longitude,entry.latitude],
记录的时间=条目。记录的时间
)
用于日志_条目中的条目
]
GeoLogEntry.objects.bulk\u创建(geo\u log\u条目,忽略\u冲突=True)
因此,我们批量获取我们需要链接到的所有对象(因此只有一个查询),制作一个映射主键上经度和纬度的字典,然后将
location\u point\u id
设置到该点


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

问题是,对于大多数数据库来说,它不会填充对象中的主键,因此这意味着不能使用这些来为
位置\u点
赋值,对于创建的对象,PK为空。@WillemVanOnsem AFAIK使用Postgres 12和Django 3就足以设置主键。OP指定他正在使用Django 3.1.2和PostgreSQL 12。4@artem嗯,那好吧。我只是觉得我做过一次。。。说明必须设置主键,但我假设它是
lambda point:LocationPoint(latitude=point.latitude,…)
,因此
point.latitde
而不是
latittude
?我还可以推荐一种脏的解决方案。如果您实际上不需要将创建的对象作为responseThanks返回,则使用类似于芹菜的东西异步执行该部分!对于1000条记录上的查询(86毫秒对1100毫秒),这要快得多,但在Python方面仍然很慢(4.4秒对16秒)。关于如何优化它有什么建议吗?@artem:对于字典来说,这应该不会太慢。对于线性搜索,这当然是另一回事。您也许可以尝试分析性能差距的确切位置。似乎这只是调试模板呈现时间(+调试工具栏成本),创建
数据
时间成本随着记录计数的增长而快速增长(在python端创建
数据
需要10秒),但我想我会对其进行优化。再次感谢:)
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)