Cole
Cole

Reputation: 2509

Django: how do I code methods in abstract class which rely on a manager?

I understand that an abstract model has no manager. When an abstract model is used to create a real model, the real model has a manager (objects) to make queries. I would like to write code in the abstract model which involves get certain query result, but instead, I essentially force such code to be written in the real model. Here is a simple version of the problem. Is there a way to write code for prior quarter in the abstract model Quarter?

class Quarter(models.Model):
    quarter_code = models.IntegerField()  # e.g. 20141 > quarter 1 for 2014
    result = models.FloatField()

    class Meta:
        abstract = True

    @property
    def prior_quarter_code(self):
        return self.quarter_code - (self.quarter_code % 10 == 1 and 7 or 1)

    @property
    def prior_quarter(self):
        # what I would like:
        #
        # return Quarter.objects.get(quarter_code=self.prior_quarter_code)
        #
        # what I write

        assert False, "method must be written against a non abstract model"

    def change_in_results(self):
        return self.result - self.prior_quarter.results

class Company(Quarter)
    @property
    def prior_quarter(self):
        return Company.objects(quarter_code=self.prior_quarter_code)

Upvotes: 1

Views: 54

Answers (1)

Daniel Rucci
Daniel Rucci

Reputation: 2872

You could get the manager using

self.__class__.objects.get(quarter_code=self.prior_quarter_code)

Upvotes: 2

Related Questions