将 Django 模型映射到外部 API [英] Map Django Model to External API

查看:29
本文介绍了将 Django 模型映射到外部 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆