根据需要向文档添加字段
假设我有这个文档:
from mongoengine import Document, EmbeddedDocument, fields
import datetime
class EmbeddedColumn(EmbeddedDocument):
created = fields.DateTimeField(default=datetime.datetime.now)
class Dattum(Document):
datasource_id = fields.IntField(required=True)
date_modified = fields.DateTimeField(default=datetime.datetime.now)
point = fields.GeoPointField()
columns = fields.ListField(fields.EmbeddedDocumentField(EmbeddedColumn))
在运行时,我需要根据一系列查询向某些实例添加一些字段:
for row in csv_attach:
dato = Dattum(datasource_id=datasource.pk)
for column in columns:
col_dict = model_to_dict(column)
col_dict.pop('id')
ecol = EmbeddedColumn(**col_dict)
dato.columns.append(ecol)
if ecol.geodata_type=='point':
local_search = gmaps.local_search('%s %s' %(ecol.value, region))
results = local_search['responseData']['results']
result_len =
if len(results) == 1:
result = results[0]
#dato.point(result['lat'], result['lng'])
dato.geojson = geojson.Point(dato.point)
dato.save()
当我检索一些 Dattum 时,我看到它具有正确的列,但没有列具有来自 model_to_dict( column) 和 dato 没有属性 geojson。
可能我对 mongoengine 的要求太多了,也许有一个合适的方法来解决这个问题。 有什么指针吗?
say I have this documents:
from mongoengine import Document, EmbeddedDocument, fields
import datetime
class EmbeddedColumn(EmbeddedDocument):
created = fields.DateTimeField(default=datetime.datetime.now)
class Dattum(Document):
datasource_id = fields.IntField(required=True)
date_modified = fields.DateTimeField(default=datetime.datetime.now)
point = fields.GeoPointField()
columns = fields.ListField(fields.EmbeddedDocumentField(EmbeddedColumn))
At runtime i need to add some field to some instances according to a series of queries:
for row in csv_attach:
dato = Dattum(datasource_id=datasource.pk)
for column in columns:
col_dict = model_to_dict(column)
col_dict.pop('id')
ecol = EmbeddedColumn(**col_dict)
dato.columns.append(ecol)
if ecol.geodata_type=='point':
local_search = gmaps.local_search('%s %s' %(ecol.value, region))
results = local_search['responseData']['results']
result_len =
if len(results) == 1:
result = results[0]
#dato.point(result['lat'], result['lng'])
dato.geojson = geojson.Point(dato.point)
dato.save()
When I retrieve some Dattum I see that it has the proper columns, but the no columns has fields from model_to_dict(column)
and dato have no attribute geojson.
May be I'm asking too much magic to mongoengine, may be there is a proper way to tackle this.
Any pointer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我同意 dcrosta - 使用 DictField 而不是 EmbeddedDocument - 您对创建日期没有验证,除了您可以灵活地存储数据之外,与 EmbeddedField 相同。
I agree with dcrosta - use a DictField instead of an EmbeddedDocument - you have no validation on the created date, other than that you get a flexible store for your data, the same as an EmbeddedField.
mongoengine 中尚不支持此功能。
虽然github上似乎有关于这个问题的讨论
This feature is not yet available in mongoengine.
Although there seems to be dicussion regarding this issue in github