我是Django的新手,尤其是它的继承工具。 我有以下架构:
class BaseMixin(models.Model):
effective_from = models.DateTimeField(blank = True, null = True)
class Meta:
abstract = True
class QuerySetManager(models.Manager):
def get_queryset(self):
# ...
def __getattr__(self, attr, *args):
return getattr(self.get_queryset(), attr, *args)
def save(self, *args, **kwargs):
# I want this method to be deployed for my_model_instance.save()
class MyModel(BaseMixin):
# ...
objects = QuerySetManager()
class Meta:
managed = False
db_table = 'my_model'
class QuerySet(QuerySet):
# ...
所以我的目标是在尝试保存对my_model_instance的更改时调用QuerySetManager
的{{1}}方法。问题是,我应该在save
中重载save
方法吗?还是在BaseMixin
?我绑两个,就像现在一样,Django在这两种情况下都忽略了我的自定义保存方法。
答案 0 :(得分:2)
您的BaseMixin是您在其他地方继承的抽象类。
ModelManagers没有提供保存方法,它用于在查询特定模型时抽象出复杂的逻辑。
您需要在此处覆盖保存MyModel。就像是。
class MyModel(BaseMixin):
# ...
objects = QuerySetManager()
class Meta:
managed = False
db_table = 'my_model'
def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
print "In Save Method"
return super(MyModel, self).save()
Save方法是模型实例的属性。
简单示例。
def my_view(request,pk):
my_model = MyModel.object.get(id=pk)
my_model.field_1 = "new value"
## When you call save method your custom save method is called first.
my_model.save()