Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 448
innospark Avatar asked Mar 31 '13 05:03

innospark


People also ask

Is SAVE called on create Django?

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.

What does save () do in Django?

save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.

How do I save an object in Django?

To save changes to an object that's already in the database, use save() . This performs an UPDATE SQL statement behind the scenes. Django doesn't hit the database until you explicitly call save() .

Which method is used to save a model in DB in Python Django?

Saving objects. To save an object back to the database, call save() : Model.


1 Answers

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.

like image 167
Burhan Khalid Avatar answered Sep 27 '22 22:09

Burhan Khalid