Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a Django model method from a template

Tags:

python

django

I have a model like this:

class Car(models.Model):
    parentType = models.ForeignKey("self", null=True,blank=True)
    engine = models.TextField (null=True)

A car can have an engine or be a variant of another car with the same engine. Right now I have an accessor like this:

def GetEngine(self):
    if self.parentType:
        return self.parentType.GetEngine()
    return self.engine

But this is quickly getting ugly with templates, as I need a property to access (cannot call the function) and then I end up with properties named nearly the same as the fields. Is there a way to express the behaviour above directly within Django?

like image 981
Anteru Avatar asked Sep 11 '26 02:09

Anteru


1 Answers

If the model method doesn't take arguments (beyond self), it'll work just fine in the template with this syntax (notice no parentheses)

{{ car.GetEngine }}

The more general issue of overshadowing a model field with a property/setter/getter is more difficult and prone to caveats, ref https://code.djangoproject.com/ticket/3148

When this happens unless it's a big deal you might just want to use a different property name, or a template tag etc

like image 83
bakkal Avatar answered Sep 13 '26 16:09

bakkal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!