Jim
Jim

Reputation: 14270

Using Python Objects in Django Applications

I apologize if this seems like a stupid question but I'm still very much a novice Python/Django programmer. Is it normal to create Python objects in a Django application that aren't models that will be saved in the database?

I'm creating what's become a fairly large Django application and, to me, my code is really starting to "smell". What I mean is that my views are becoming very large because I'm taking a procedural rather than object-oriented approach. My intuition tells me that my code might be simpler, easier to test, and more robust in the long run if I were using more objects with their own attributes and behaviors rather than passing information from one function to the next in my views.

What's hanging me up is that these aren't objects I want to save in my database so I don't quite know if I should be using them and, if I should, where I'd put them. Is the approach I'm proposing typical in a Django application? If so, where would I store those objects with respect to the Django model/view/template structure? Also, are there any popular Django modules or libraries that do what I'm describing that I should study?

Thanks in advance for your response.

Upvotes: 5

Views: 555

Answers (2)

dm03514
dm03514

Reputation: 55962

You can store your objects anywhere. There could be helper functions in your views file or models file or wherever. I prefer to put miscellaneous functions in a utils.py file but that is not a convention, just something I end up doing. I end up putting most of miscellaneous helper functions and base classes in a common app, and more specifically a common.utils file.

In one project I have lots of apps, and each app has an api client. The base class for the client resides in an app called common. Then each app then has their specific client in client.py file

  • project
    • common
      • client
    • app1
      • client
    • app2
      • client

Then in app1 client

from project.common.client import BaseClient

class ConcreteApp1Client(BaseClient):
  pass

Then in my views or management commands or models or wherever the concrete client can be imported and used as normal. from project.app1.client import ConcreteApp1Client

Upvotes: 1

jaynp
jaynp

Reputation: 3325

Django also has class-based views if you feel certain variables could best be encapsulated in a class.

https://docs.djangoproject.com/en/dev/topics/class-based-views/

Upvotes: 0

Related Questions