Using Python Objects in Django Applications

I apologize if this seems like a stupid question, but I'm still a very beginner Python / Django programmer. Is it okay to create Python objects in a Django app that are not models to be stored in the database?

I'm building what has become a pretty large Django application, and for me my code is really starting to smell. I mean my views get very big because I am taking a procedural rather than an object oriented approach. My intuition tells me that my code can be simpler, easier to test, and more reliable in the long run if I use more objects with their own attributes and behaviors rather than passing information from one function to the next in my views.

What hangs me up is that these are not objects that I want to store in my database, so I am not entirely sure if they should be used, and if so, where would I put them. Is the approach I am suggesting typical in a Django application? If so, where will I store these objects in relation to Django structure / view structure / template? Also, are there any popular Django modules or libraries out there that do what I'm describing that I should learn?

Thanks in advance for your reply.

+3


source to share


2 answers


You can store your objects anywhere. There can be helper functions in your view file or model file or wherever you like. I prefer to put different functions in a file utils.py

, but that's not a convention, it's just something I'm doing. In the end, I add most of the helper functions and base classes to the application common

, more specifically the file common.utils

.

In one project I have many applications and each application has an api client. The base class for the client is in the app called common

. Then each application has its specific client in the client.py

file

  • Project
    • general
      • customer
    • app1
      • customer
    • app2
      • customer


Then in app1 client

from project.common.client import BaseClient

class ConcreteApp1Client(BaseClient):
  pass

      

Then in my views or control commands or models or wherever a particular client can be imported and used as usual. from project.app1.client import ConcreteApp1Client

+1


source


Django also has class-based views if you think certain variables are best encapsulated in a class.



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

0


source







All Articles