Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

Is save() called implicitly when calling create in django?

I'm trying to perform some custom validation on a model and I'm getting confused. Let me be specific. Let's say my code is as follows:

class FooManager(models.Manager):
  def create_foo(self, name):
    return self.create(foo_name = name)

class Foo(models.Model):
  foo_name = models.CharField(max_length=30)
  objects = FooManager()

  def clean(self):
    ...
  def save(self, *args, **kwargs):
    self.full_clean()
    super(User, self).save(*args, **kwargs)

Now, when I am working with this model from the shell, if I call:

f = Foo.objects.create_foo("")

It will raise a validation error before I get a chance to call save() on f. Why does this happen? Shouldn't the validation error only be raised once I call f.save()?

Note: the same thing happens if I use objects.create() as opposed to the custom defined create method. Any help would be greatly appreciated, as I'm finding validations in django to be fairly frustrating.

question from:https://stackoverflow.com/questions/15726553/is-save-called-implicitly-when-calling-create-in-django

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

create() will automatically save, so even if you fix your error - you will still have to make sure the arguments to create fulfill the database requirements to save a record.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...