This might be a stupid question, but here goes…
If i have a view which returns data to a dashboard. Within the view i want retrieve all types of different data from different models.
For example; I have an Event
model that contains details of events.On the dashboard i want to show events due today. tomorrow, next quarter etc. So in my view i have some logic (Not sure how yet).
I also have a Project
model. Within the same view i am getting all the information relating to different projects, such as types of projects, reviews etc, with the logic all being in the same view.
Once i’ve worked out what the logic needs to be to get all the data the view could be pretty big. Should i be breaking each piece of logic into differnt functions
and then is it possible to execute the function
from within the view
or should all the login remain within the view? How do you share between views?
Hope this makes sense?
First, never lose sight of the fact that a Django view is just a Python function that takes a request and returns a response. There’s nothing special or magical about it.
This means you have all the “code organization” facilities available as with any other Python program.
Yes, it’s absolutely ok to break the functionality of the view down into different modules.
Where you physically place that logic is a topic open for (a lot of) discussion. For examples, see the discussions here - Where to put business logic in Django? and here - Structuring large/complex Django projects, and using a services layer in Django projects. (So no, this is far from being a “stupid question” - it wouldn’t generate this amount of conversation if it were.)
Regardless of the organizational structure you adopt, I think it’s most important that you remain consistent within and among projects. Given Python’s flexibility, the issue is that there’s so many different ways of doing this, you want to “minimize surprise” when you (or a teammate) need to go back into the code later to maintain or update it. And that implies having a consistent pattern applied throughout.
1 Like