lundi 21 avril 2014

Puis-je créer des modèle de django, qui ne sera pas rendue persistante dans la base de données ? -Débordement de pile


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




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.




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()


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



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.



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()

0 commentaires:

Enregistrer un commentaire