Model.objects.create equivalent that performs a full_clean?

安稳与你 提交于 2019-12-23 17:51:04

问题


So I've got the following code:

class MyModel(models.Model):
    # Text language.                                                                                 
    ENGLISH = 'eng'                                                                                   
    FRENCH  = 'fr'                                                                                   

    LANGUAGES_CHOICES = [                                                                            
        (ENGLISH, 'English'),                                                                        
        (FRENCH, 'French'),                                                                          
    ]                                                                                                

    language = models.CharField(                                                                     
            max_length=max(len(language) for language in LANGUAGES_CHOICES),                         
            choices=LANGUAGES_CHOICES,                                                               
            blank=False,                                                                             
            null=True)

When I do MyModel(language='invalid').save() or MyModel.objects.create(language='invalid'), the model is saved without complaint. Is there any convenience method that is equivalent to Model.objects.create that performs a full_clean before it saves?


回答1:


If you are using model forms, the full_clean will be called as part of the form validation step.

In general, there isn't a convenience method that calls full_clean, but you could write your own.




回答2:


Model.clean(): This method should be used to provide custom model validation, and to modify attributes on your model if desired. For instance, you could use it to automatically provide a value for a field, or to do validation that requires access to more than a single field:



来源:https://stackoverflow.com/questions/21939045/model-objects-create-equivalent-that-performs-a-full-clean

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