2 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
主要問(wèn)題是獲取要批量鏈接的對(duì)象。一旦我們存儲(chǔ)了所有這些對(duì)象,我們就可以批量獲取對(duì)象:
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)
因此,我們批量獲取需要鏈接到的所有對(duì)象(因此使用一個(gè)查詢),創(chuàng)建一個(gè)映射主鍵上的經(jīng)度和緯度的字典,然后設(shè)置為該點(diǎn)location_point_id。
然而,重要的是使用小數(shù),或者至少是一種匹配的類型。浮點(diǎn)數(shù)很棘手,因?yàn)樗鼈兒苋菀桩a(chǎn)生舍入誤差(因此經(jīng)度和緯度通常存儲(chǔ)為“定點(diǎn)”數(shù)字,例如整數(shù)大 1'000 倍或大 1'000'000 倍)。否則,您應(yīng)該使用將其與通過(guò)查詢生成的數(shù)據(jù)相匹配的算法。

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個(gè)贊
bulk_create(...)將以列表形式返回您創(chuàng)建的對(duì)象。您可以在 Python 端過(guò)濾這些對(duì)象,而不是查詢數(shù)據(jù)庫(kù),因?yàn)樗鼈円呀?jīng)被獲取。
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)
您所需要做的就是實(shí)現(xiàn)get_location_point滿足您的需求
添加回答
舉報(bào)