Could someone please explain what the following means:
"Business logic belongs in the model, but view logic belongs in the view."
What is the general distinction for each as well as a few examples. Thank you.
Could someone please explain what the following means:
"Business logic belongs in the model, but view logic belongs in the view."
What is the general distinction for each as well as a few examples. Thank you.
You could've just asked in the comments on the other question ;).
Business logic is anything that's related to how a "thing" works or operates. Take for example the following:
class Animal(Object):
def speak(self, sound):
print sound
class Duck(Animal):
has_feathers = True
It would be incorrect to do something like:
>>> myduck = Duck()
>>> myduck.speak('Quack!')
Quack!
The fact that a duck makes the sound of 'Quack!' is business logic, and should be in the model:
class Duck(Animal):
has_feathers = True
makes_sound = 'Quack!'
def speak(self):
super(Duck, self).speak(self.makes_sound)
You don't necessarily need to understand all that; all we're doing is ensuring that when a Duck
speaks it says 'Quack!':
>>> myduck = Duck()
>>> myduck.speak()
Quack!
View logic would be anything related to processing a request and returning some sort of response. Using the previous example, our view would contain the code to instantiate a Duck
object and make it speak.
myduck = Duck()
myduck.speak()
The "response" would be the 'Quack!'.
Just improving the last answer if you are new in Django is a good pratice to make your business logic and view logic separated, us business logic should be in you model or any file at that level, and you views only have to call objects and method to return data to you views, you should not process the data (i mean chance the data or put any aditional logic) at you views, if you need to change something at you main method logic, you should change in you method, but if you want to keep the main method logic you should then create a new method to handle this new condition