1
class Post(AnoterModelMixin, AANotherModelMixin, models.Model):
這是什麼意思,如果它在models.py
爲django?Django中models.Model的類MyModel(...,models.Model)的多個參數是什麼意思?
class Post(AnoterModelMixin, AANotherModelMixin, models.Model):
這是什麼意思,如果它在models.py
爲django?Django中models.Model的類MyModel(...,models.Model)的多個參數是什麼意思?
實際上,這是組織代碼的一種非常方便的方式。 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 '
多重繼承... – Yaaaaaaaaaaay