1
class Post(AnoterModelMixin, AANotherModelMixin, models.Model):

What does this mean if it's in models.py for django?

Victor Sergienko
  • 13,115
  • 3
  • 57
  • 91
lip123809
  • 89
  • 7

1 Answers1

0

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 '
Community
  • 1
  • 1
djq
  • 14,810
  • 45
  • 122
  • 157