in one of my Django models I have to add specific code for each model instance. Now, I wonder what would be a good way to implement this. My current attempt results in a big, hard to read if statement.
Consider the following model:
class Foo(models.Model):
name = models.CharField(max_length=255)
def do_instance_specific_stuff(self, arg):
if self.id == 1:
do_X(arg)
elif self.id == 2:
do_Y(arg)
else:
do_Z()
Right now, there is custom code for around 20 model instances and it will stay in this magnitude. Any ideas or patterns how this can be implemented in a clean, readable way?
Thanks for any help.
I would add another field to your model,
vendor. Then add per-vendor methods to your model, and invoke them with getattr:Depending on particular values of
idseems very fragile. In your data model, each vendor string will appear only once, but it will be readable and malleable. You can decide what you want to do if thegetattrcan’t find the vendor code.