2 回答

TA貢獻1802條經驗 獲得超5個贊
主要問題是獲取要批量鏈接的對象。一旦我們存儲了所有這些對象,我們就可以批量獲取對象:
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 倍)。否則,您應該使用將其與通過查詢生成的數據相匹配的算法。

TA貢獻1873條經驗 獲得超9個贊
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滿足您的需求
添加回答
舉報