上下文
我有一个外部 API 提供数据并允许发布新数据或修补现有数据。
API 响应示例:
response = requests.get('http://api/band/4/')
print(response.json()) # {id: 4, name: 'The Beatles'}
当我操作 API 提供的这些对象时,我希望它们像 Django 模型的实例一样:我希望像对象一样使用它们,并能够创建与 API 提供的这些模型的关系。
我可以通过创建标准模型并在需要时填充来巧妙地复制数据库中的数据,但我真的不想这么做。
操纵示例:
class Band(Model): # should not create a new table in database but use API requests instead
id = PrimaryKey()
name = StringField()
class User(Mode):
favourite_band = ForeignKey(Band) # I want to be able to give an instance or directly the pk of a Band
问题
你知道我该怎么做吗?也许为这些特定模型编写我自己的数据库引擎,其实例由 api 提供?或者只是一个自定义 ModelField ?
也许你可以尝试这样的事情..
response = requests.get(........)
response_data = response.json()
item = Band(**response_data)
#do something with instance.
现在,该项目是 Band 的一个实例。您可以对实例进行操作。仅当执行 item.save() 命令时,它才会写入数据库。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)