class Post(AnoterModelMixin, AANotherModelMixin, models.Model):
What does this mean if it's in models.py
for django?
class Post(AnoterModelMixin, AANotherModelMixin, models.Model):
What does this mean if it's in models.py
for django?
Practically, it's a really convenient way of organizing your code. A mixin is a special kind of multiple inheritance.
AnoterModelMixin
can contain a set of methods that you can use on your model; these are inherited:
class Post(AnoterModelMixin, AANotherModelMixin, models.Model):
name = models.CharField(max_length=150)
AnoterModelMixin
could look like this:
class AnoterModelMixin(object):
"""Additional methods on the Post model"""
def get_short_name(self):
"""Returns the first 10 characters of the post name"""
return self.name[:10]
def get_longer_name(self):
"""Returns the first 15 characters of the post name"""
return self.name[:15]
You can then use it like so:
demo_post = Post.objects.create(name='This is a very long post name')
demo_post.get_short_name() # 'This is a '
demo_post.get_longer_name() # 'This is a very '