2016-02-03 37 views

回答

0

實際上,這是組織代碼的一種非常方便的方式。 A mixin is a special kind of multiple inheritance

AnoterModelMixin可以包含一組您可以在模型上使用的方法;這些被繼承:

class Post(AnoterModelMixin, AANotherModelMixin, models.Model): 
    name = models.CharField(max_length=150) 

AnoterModelMixin看起來是這樣的:

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] 

然後,您可以使用它,像這樣:

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 ' 
相關問題