Can I create django model, which will be not persisted in database?

百般思念 提交于 2020-01-01 06:51:10

问题


As asked in question: Can I create django model(models.Model), which will be not persisted in database?

The reason is I want use it in my django admin to build custom form basing on forms.ModelForm


回答1:


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

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.

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.




回答2:


It's easier to just use forms.Form:

class UserForm(forms.Form):
    first_name = forms.CharField(max_length=100)
    last_name = forms.CharField(max_length=100)
    email = forms.EmailField()


来源:https://stackoverflow.com/questions/22690330/can-i-create-django-model-which-will-be-not-persisted-in-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!