通过ndb.Model构造函数填充StructuredProperty的最佳实践是什么? [英] What is the best practice to populate a StructuredProperty through the ndb.Model constructor?
问题描述
我查看了ndb
GitHub示例代码,但找不到任何示例
其中显示了如何使用包含StructuredProperty
的构造函数创建ndb
实体.
I looked into the ndb
GitHub sample code, but I couldn't find any example
which shows on how to create a ndb
entity with a constructor that contains a StructuredProperty
.
这是GitHub 示例.
如果我想用电话号码列表初始化Contact
实体,而该电话号码列表不是PhoneNumber
对象列表,该怎么办.相反,它是Python词典的列表.
What if I want to initialize a Contact
entity with a list of phone numbers and this list of phone number is not a list of PhoneNumber
objects. Instead it is a list of Python dictionaries.
因此,给定以下Model
类:
class PhoneNumber(ndb.Model):
"""A model representing a phone number."""
phone_type = ndb.StringProperty(
choices=('home', 'work', 'fax', 'mobile', 'other'))
number = ndb.StringProperty()
class Contact(ndb.Model):
"""A Contact model that uses StructuredProperty for phone numbers."""
# Basic info.
name = ndb.StringProperty()
birth_day = ndb.DateProperty()
# Address info.
address = ndb.StringProperty()
phone_numbers = ndb.StructuredProperty(PhoneNumber, repeated=True)
我想使用以下Python字典创建Contact
:
I want to create a Contact
using the following Python dictionaries:
phone_number_dicts = [{"phone_type" : "home", number = 122}, {"phone_type" : "work", number = 123}]
contact = Contact(name = "some name", birthday = "some day", phone_numbers = phone_number_dicts)
- 我需要明确地将字典转换为
ndb
实体吗? - 我可以重写将字典转换为
ndb
实体并进行赋值的ndb
构造函数吗? - 还有其他更好的方法吗?
- Am I required to convert a dict to a
ndb
entity explicitly? - Can I override
ndb
constructor which converts a dict to andb
entity and assign? - Any other better approach?
推荐答案
代替
phone_number_dicts = [{"phone_type" : "home", number = 122}, {"phone_type" : "work", number = 123}]
contact = Contact(name = "some name", birthday = "some day", phone_numbers = phone_number_dicts)
您需要具有以下内容:
phone_numbers = [
PhoneNumber(phone_type="home", number=123),
PhoneNumber(phone_type="work", number=123)
]
contact = Contact(name="some name", birthday="some day", phone_numbers=phone_numbers)
即列出PhoneNumber
个实体,而不是dict
个.
i.e. make a list of PhoneNumber
entities rather than a list of dict
s.
您也可以将字典传递给ndb实体,以便使用 populate
方法,即如果您已经有了该行
You may also pass a dict to an ndb entity in order to populate it with the populate
method, i.e. if you already have the line
phone_number_dicts = [{"phone_type" : "home", number = 122}, {"phone_type" : "work", number = 123}]
您无法控制,然后就可以
that you have no control over, you could then do
phone_numbers = [PhoneNumber().populate(**entity) for entity in phone_number_dicts]
从现有的dict
列表中创建PhoneNumber
的列表,然后将其再次传递给Contact
构造函数.
to create a list of PhoneNumber
s from an existing list of dict
s which you then again pass to the Contact
constructor.
这篇关于通过ndb.Model构造函数填充StructuredProperty的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!