M
M
maxclax2014-12-26 02:31:55
Django
maxclax, 2014-12-26 02:31:55

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)

Next, using this model, where necessary, I call the rate () method. So I'm confused by the fact that some logic (counting) lies in my model. The model, in fact, should not contain any logic in itself. 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? Perhaps for this you need to implement your manager.py

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Ilya, 2014-12-26
@FireGM

The model, in fact, should not contain any logic in itself.

Why? If it works with one instance of the model, then it is in it that the method must be made.
Managers are needed for something else. There's more work with QuerySets.

R
Rostislav Grigoriev, 2014-12-26
@crazyzubr

I am confused by the fact that some logic (counting) lies in my model

what language/framework did you switch to django from? it shouldn't bother you at all.
I can only advise using the decorator @propertyor @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

PS
the question is removed, I remembered: PHP and Symphony 2 =)

A
Alexey Yeletsky, 2014-12-26
@Tiendil

> 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 question

Ask a Question

731 491 924 answers to any question