Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models using API instead of database

I am fairly new to Django and have some requirements that involve creating a Django application to be the front end for an API server.

This app should have little need to ever store data in a local database. Instead, we are to access a REST API to get and post data.

Being less familiar with the framework, where should I be placing the logic for getting and manipulating data on the remote API? My initial thought was to place this into the models.py file, but models seem to be designed specifically for database access in Django.

So then I placed request calls in my form classes's get/post functions. However, this seems like I am mixing up the data logic with the views. Also, I noticed that reloading pages after posting a form would result in the form containing the original GET request for the form until I restarted the server.

It appears that I should be placing this logic elsewhere, but I'd like someone to explain what is "standard" in this context.

I am sure I not the first person to encounter this and would like some direction on how other projects handle this in Django. Thank you for your guidance.

like image 716
Terry Avatar asked Oct 29 '22 06:10

Terry


1 Answers

I'm working on a similar problem when I'm trying to wrap the Django ORM around an API, and I'm surprised that no one else has done something like this before. (Or at least they haven't made a public gist or blogpost about it.)

I think your intuition is right that the logic probably shouldn't go in the view or forms. Ideally it would be lower-level (Model, Manager, Queryset or lower), so that you get all the benefits of the rest of Django.

I think the most ideal way to do this would be to create a custom database backend that simulates the functionality of a database, while interacting directly with the API.

Here is a high-level overview of what that entails: http://reinout.vanrees.org/weblog/2016/11/04/database-backends.html

Also, if you look at the Django sourcecode, you could probably use django/db/backends/dummy/ as a starting point for how the code should be structured.

like image 63
ninapavlich Avatar answered Nov 15 '22 07:11

ninapavlich