O
O
ooker2020-11-25 16:04:32
Django
ooker, 2020-11-25 16:04:32

How to refer to a function in a model?

Hello.
Question for the experts. I want to remove a condition from the template into the model.
models.py

master_promo_count = models.SmallIntegerField(default=0, verbose_name='Количество дней акции',)
 # СЧЕТЧИК АКЦИИ
    def promo(self, *args, **kwargs):
        self.master_promo_count = (self.master_date_end - datetime.today().date()).days
        return self.master_promo_count

    # Замена словаря в шаблоне
    def master_promo_count_day(self, *args, **kwargs):
        if self.promo(self, *args, **kwargs) == 1:
            return f'день'
        elif self.promo(self, *args, **kwargs) == 2:
            return f'дня'
        else:
            return f'дней'

html
<span class="red-text bb f18">{{ obj.promo }} {{ obj.master_promo_count_day }}</span></div>

If you do it like this, then everything works.
# Замена словаря в шаблоне
    def master_promo_count_day(self):
        if self.master_promo_count == 1:
            return f'день'
        elif self.master_promo_count == 2:
            return f'дня'
        else:
            return f'дней'

If you access the column to the table, everything works, if the first function does not.
Who will correct what I'm doing wrong?
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2020-11-25
@fox_12

You generally have a game with the code ...
This is:

master_promo_count = models.SmallIntegerField(default=0, verbose_name='Количество дней акции',)
 # СЧЕТЧИК АКЦИИ
    def promo(self, *args, **kwargs):
        self.master_promo_count = (self.master_date_end - datetime.today().date()).days
        return self.master_promo_count

easily changed to this:
@property
def master_promo_count(self):
      return (self.master_date_end - datetime.today().date()).days

And then this will work:
def master_promo_count_day(self):
        if self.master_promo_count == 1:
            return f'день'
        elif self.master_promo_count == 2:
            return f'дня'
        else:
            return f'дней'

And generally this:
<span class="red-text bb f18">{{ obj.promo }} {{ obj.master_promo_count_day }}</span></div>

like master_promo_count_day - in general, it is better to do it through templatetags if the regular pluralize does not fit

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question