Hanpan
Hanpan

Reputation: 10251

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?

Upvotes: 3

Views: 7456

Answers (2)

Luke Sneeringer
Luke Sneeringer

Reputation: 9428

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. :)

Upvotes: 7

Henry
Henry

Reputation: 6620

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.

Upvotes: 3

Related Questions