我可以创建将不会持久保存在数据库中的Django模型吗? [英] Can I create django model, which will be not persisted in database?
问题描述
有问题的情况:
我可以创建将不会持久保存在数据库中的Django模型(models.Model)吗?
As asked in question: Can I create django model(models.Model), which will be not persisted in database?
原因是我想要在我的django管理员中使用它来基于forms.ModelForm
The reason is I want use it in my django admin to build custom form basing on forms.ModelForm
推荐答案
您可以覆盖模型的 save()
方法来防止保存到数据库,并使用 managed = False
来防止Django创建适当的表:
You can override the model's save()
method to prevent saving to the database, and use managed = False
to prevent Django from creating the appropriate tables:
class NonPersistantModel(models.Model):
def save(self, *args, **kwargs):
pass
class Meta:
managed = False
当批量操作尝试保存该模型的实例时,这将引发错误,因为将不使用 save
方法,并且该表将不存在。在您的用例中(如果您只想使用模型来构建 ModelForm
),应该没问题。
Note that this will raise an error when a bulk operation tries to save instances of this model, as the save
method wouldn't be used and the table wouldn't exist. In your use-case (if you only want to use the model to build a ModelForm
) that shouldn't be a problem.
但是,我强烈建议您将表单构建为 forms.Form
的子类。模型是数据库表的抽象,普通形式可以完成生成的 ModelForm
可以做的一切,甚至更多。
However, I would strongly recommend building your form as a subclass of forms.Form
. Models are abstractions for your database tables, and plain forms are capable of anything a generated ModelForm
can do, and more.
这篇关于我可以创建将不会持久保存在数据库中的Django模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!