以下是一个示例记录:
{
"_id": { "$oid" : "51376F833EF9EB361F354ED0" },
"addresses": [
{
"city": "CAMBRIDGE",
"suffix": "",
"street_name": "FRANKLIN ST",
"prefix": "",
"zipcode": "49503",
"state": "MA",
"street_num": "127"
}
],
"created_at":{ "$date": 1361160419000.000000 }
}
这是我的班级代码:
class Buildings(db.Document):
_id = db.ObjectIdField(required=True)
addresses = db.ListField(db.EmbeddedDocumentField('Address'))
created_at = db.DateTimeField(default=datetime.datetime.now, required=False)
meta = {
'allow_inheritance': False,
'indexes': ['_id'],
'ordering': ['-created_at']
}
class Address(db.EmbeddedDocument):
city = db.StringField(required=False)
suffix = db.StringField(required=False)
street_name = db.StringField(required=False)
zipcode = db.StringField(required=False)
prefix = db.StringField(required=False)
state = db.StringField(required=False)
is_contracted = db.IntField(required=False)
street_num = db.StringField(required=False)
一个循环应该打印嵌入的Document但只为每个对象返回一个[]。
for building in Buildings.objects:
print building.addresses
知道为什么这不起作用?
答案 0 :(得分:2)
尝试检查您的代码如何在mongodb中存储记录:
address = Address(**{
"city": "CAMBRIDGE",
"suffix": "",
"street_name": "FRANKLIN ST",
"prefix": "",
"zipcode": "49503",
"state": "MA",
"street_num": "127"
})
Buildings(_id=ObjectId(), addresses=[address]).save()
您会看到下一个结果:
{
"_id": ObjectId("5146e17969d90d0f124536ee"),
"addresses": [{
"_types": ["Address" ],
"city": "CAMBRIDGE",
"suffix": "",
"street_name": "FRANKLIN ST",
"state": "MA",
"zipcode": "49503",
"prefix": "",
"_cls": "Address",
"street_num": "127"
}],
"created_at" : ISODate("2013-03-18T12:42:17.389Z")
}
我将您的模型实现为:
class Address(db.EmbeddedDocument):
city = db.StringField()
suffix = db.StringField()
street_name = db.StringField()
zipcode = db.StringField()
prefix = db.StringField()
state = db.StringField()
is_contracted = db.IntField()
street_num = db.StringField()
meta = {
'allow_inheritance': False,
}
class Buildings(db.Document):
addresses = db.ListField(db.EmbeddedDocumentField(Address))
created_at = db.DateTimeField(default=datetime.datetime.now)
meta = {
'allow_inheritance': False,
'indexes': ['_id'],
'ordering': ['-created_at'],
}
将记录存储为:
{
"_id": ObjectId("5146e2b069d90d0f2cc3911a"),
"addresses": [{
"city": "CAMBRIDGE",
"suffix": "",
"street_name": "FRANKLIN ST",
"state": "MA",
"zipcode": "49503",
"prefix": "",
"street_num": "127"
}],
"created_at": ISODate("2013-03-18T12:47:28.939Z")
}
我不知道如何使用字段"_id": { "$oid": "51376F833EF9EB361F354ED0"}
和"created_at":{"$date": 1361160419000.000000}
保存文档,但我认为存在问题。
required
字段参数为False
。
EmbeddedDocumentField
和ReferenceFiled
可以获取参数EmbeddedDocument
和Document
类或字符串('self'
以供自我参考)。
如果你想把id作为对象,你也必须在代码中使用它。
如果您想要另一种日期时间格式,则必须使用ComplexDateTimeField
或使用基类ComplexDateTimeField
实现。