M
M
maxclax2015-04-05 17:53:50
Django
maxclax, 2015-04-05 17:53:50

How to call a method on a linked table?

I have two models. user and:

class Partnership(models.Model):
    class Meta:
        verbose_name = _('partnership.model.verbose_name')
        verbose_name_plural = _('partnership.model.verbose_name_plural')

    # владелец записи
    user = models.ForeignKey(User, verbose_name=_('partnership.model.user'))

    def get_amount_total(self):
        if self.transaction_set.filter(is_approved=True).count():
            # получаем суммирование всех транзакций
            data = self.transaction_set.filter(is_approved=True).aggregate(amount_total=models.Sum('amount'))
            return data['amount_total']
        else:
            return 0

Tell me this moment: can I access the get_amount_total method through User? In my understanding, it should be like this User.partnership_set.get_amount_total() but it doesn't work like that. Tried putting @property decorator doesn't work.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
X
xSkyFoXx, 2015-04-05
@xSkyFoXx

You need to explicitly inherit the get_amount_total method from User:
Since this is a framework class, rewriting it is ugly. It must be done through a proxy class or mixin (choose the design pattern that you like best).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question