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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With