Answer the question
In order to leave comments, you need to log in
How to implement logic from Django model?
I have a model:
def rate(self):
return self.course - self.course / 100 * self.deviation
currency_from = models.ForeignKey(Currency, verbose_name=_('_from'), related_name="currency_from")
currency_to = models.ForeignKey(Currency, verbose_name=_('_to'), related_name="currency_to")
course = models.DecimalField(verbose_name=_('course'), max_digits=20, decimal_places=10)
deviation = models.DecimalField(verbose_name=_('deviation'), default=0, max_digits=20, decimal_places=10)
Answer the question
In order to leave comments, you need to log in
The model, in fact, should not contain any logic in itself.
I am confused by the fact that some logic (counting) lies in my model
@property
or @cached_property
. Then it will not be necessary to call the property as a method. Example:from django.utils.functional import cached_property
@cached_property
def rate(self):
return self.course - self.course / 100 * self.deviation
# Получаем так
rate = obj.rate
> Tell me, how or where do you take out the logic of the model, which makes some changes to the model's attributes during the output?
1. The rate calculation in the example is not entirely logic. Just a model attribute that can be calculated instead of being stored. Such attributes can be left in the model.
2. It is the logic (operations on models) that is better to be separated from them - you can simply put it in a separate module. Or to the manager, if they are low-level.
3. If the object represented in the model is complex (it involves a large amount of data in different formats with a bunch of related objects, the need for caching, and so on), then it makes sense to leave the model to represent the database level (for communicating with the database, migrations, and so on), and to represent an object in logic, implement a separate class whose objects will be initialized with data from the model.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question