Adam Starrh
Adam Starrh

Reputation: 6958

Django- Staying DRY with multiple model methods

What's the preferred way to stay DRY when using model methods that require the results of another model method?

For example:

class MyModel(models.Model):
    a = models.IntegerField()
    b = models.IntegerField()
    c = models.IntegerField()

def _method_one(self):
    x = a + b    
    return x    
    method_one = property(_method_one)

def _method_two(self):
    x = a + b
    y = x + c
    return y
    method_two = property(_method_two)

def _method_three(self):
    x = a + b
    y = x + c
    z = x + y
    return z
    method_three = property(_method_three)

As more and more methods rely on the solutions of previous ones, I end up with repeating code. What's the cleanest way to handle this?

Thanks in advance.

Upvotes: 1

Views: 90

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

Why not just do:

class MyModel(models.Model):
    a = models.IntegerField(default=0)
    b = models.IntegerField(default=0)
    c = models.IntegerField(default=0)

    @property
    def x(self):
        return self.a + self.b

    @property
    def y(self):
        return self.x + self.c

    @property
    def z(self):
        return self.x + self.y

Upvotes: 2

Related Questions