我有以下型号:
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。
慕后森
眼眸繁星
相关分类