Riptyde4
Riptyde4

Reputation: 5480

Converting existing python classes into Django Models

I have a small program with a command line interface that uses a number of python classes with thorough implementations. I want to scrap the command line interface and wrap the app within a Django app, but I'm just learning Django and I'm unfamiliar with the conventions.

I have a number of classes, in-memory storage structures, getters/setters etc and I'd like to convert them into Django models so that I can persist them to the database and interact with them around the django app. Is there a general approach for doing something like this?

Should I just inherit the django.db.models.Model class in my existing classes and set them up for direct interaction? Or is there a better, more general/conventional way to do this?

I would like to be able to use all of this code in other apps, not necesarilly Django ones, so I don't really want to modify my existing classes in a way that would make them only work with Django. I thought of creating the models separately and then a sort of middle-man class to manage interaction of the actual in-memory class with the django model class, but that just seems like more places I have to make changes when I extend/modify the code.

Thanks for any help ahead of time...

Upvotes: 0

Views: 717

Answers (2)

roob
roob

Reputation: 2549

Personally, I would modify your existing classes to extend models.Model and maintain separate versions of these classes for use outside of Django.

This will keep your classes lean and maintainable within their respective environments.

You could also create a new class that extends both models.Model and your python model through multiple inheritance. However this will result in duplicate fields for the same data.

If you would like, post an example Model as a new question and tag me in a link to it here, and I can help you convert it.

Upvotes: 3

zero
zero

Reputation: 172

One of greatest django strengths is its ORM, if you want import i recommend you use it, and yes you would probably need rewrite the part that interacts with the database, but if you already have isolated this functions in a Models folder~classes, the modification won't be really hard

Although in your case i would recommending checking out Tornado/Aiohttp Since looks like you are just trying to create a interface for your functions

Upvotes: 1

Related Questions