Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 682
andilabs Avatar asked Mar 27 '14 14:03

andilabs


2 Answers

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.

like image 196
knbk Avatar answered Nov 15 '22 00:11

knbk


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()
like image 20
Koed00 Avatar answered Nov 14 '22 23:11

Koed00