【发布时间】: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