将Django模型映射到外部API [英] Map Django Model to External API
问题描述
上下文
我有一个提供数据并允许发布新数据或修补现有数据的外部API.
I have an external API providing data and allowing to post new data or patch existing one.
API响应示例:
response = requests.get('http://api/band/4/')
print(response.json()) # {id: 4, name: 'The Beatles'}
当我操纵这些对象时,API提供了我希望它们像Django模型的实例一样:我希望将它们像对象一样使用,并能够与API提供的这些模型建立关系. 我可以通过创建标准模型并在需要时进行填充来巧妙地复制数据库中的数据,但我真的不想要.
When I manipulate these objects the API provides I want them to be like instances of a Django model : I want to use them like objects and to be able to create relations to these models the API provides. I could smartly duplicate data in my database by creating standard models and populating when needed but I don't realy want to.
操作示例:
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?
Do you have any idea of how I could do that ? Maybe writing my own database Engine for these specific models whose instances are provided by the api ? or just a custom ModelField ?
推荐答案
也许您可以尝试类似的方法.
Maybe you could try something like this..
response = requests.get(........)
response_data = response.json()
item = Band(**response_data)
#do something with instance.
现在,该物品是Band的一个实例.您可以对实例进行操作.仅当执行item.save()命令时,它才会写入数据库.
Now, the item is an instance of Band. You could do the operations over the instance. It only writes to the database, only if item.save() command is executed.
这篇关于将Django模型映射到外部API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!