Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Model class interfaces?

I have a selection of models which interact with various web APIs. I need to ensure each of the models has a particular method. With PHP I'd create a class interface to ensure my model has the methods necessary to do it's job but it seems Python interfaces don't work with Django models.

I'm assuming the way to do this would be to create a base class that extends model.Model which defines the methods I need and I can overwrite them in each API model if necessary. How am I able to do this without Django picking up the "base" class when syncing the database? Is this even the right way to do it?

like image 280
Hanpan Avatar asked Jul 13 '26 00:07

Hanpan


2 Answers

You can use the abstract = True aspect of the Meta class.

class BaseModelInterface(models.Model):
    class Meta:
        abstract = True

class ActualModel(BaseModelInterface):
    [...normal model code...]

Documentation: http://docs.djangoproject.com/en/1.3/ref/models/options/

With that said, generally duck typing is considered to be "the Python way", and your calling code should test for method presence (if hasattr(instance, 'method_name')). That said, you know your particular implementation better than we do, so you can use abstract = True to get the behavior you want. :)

like image 60
Luke Sneeringer Avatar answered Jul 15 '26 12:07

Luke Sneeringer


I think this is more of a Python question. You can certainly look at Django abstract base classes but I recommend you do the more pythonic thing and not worry about trying to enforce these class interfaces. Either you implemented the method or you didn't, let the calling code deal with it.

like image 28
Henry Avatar answered Jul 15 '26 12:07

Henry



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!