43

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.

Vaibhav Mule
  • 5,016
  • 4
  • 35
  • 52
innospark
  • 778
  • 1
  • 5
  • 8

2 Answers2

39

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.

Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
  • 1
    Why does create automatically save? In the docs it says the following: "Note that instantiating a model in no way touches your database; for that, you need to save()." So what is the point of calling save(), if create() will automatically save? – innospark Mar 31 '13 at 06:26
  • 8
    That's the whole point, you don't need to call `save()` because `create()` is a shortcut to create an instance, and then save it automatically. – Burhan Khalid Mar 31 '13 at 06:31
  • ohhh, perfect. I just found the spot in the docs where it outlines this, I guess I'll try and read harder! Thanks so much, you saved me quite a bit of time Burhan! – innospark Mar 31 '13 at 06:33
  • No, do it at the last stage (at the save method). Create is a convenience method. If you forget to use it somewhere, you don't want the cleaning to not happen. – Burhan Khalid Mar 31 '13 at 06:49
0

You forgot to put self in your manager

class FooManager(models.Manager):
    def create_foo(self, name):
        return self.create(foo_name = name)
catherine
  • 22,492
  • 12
  • 61
  • 85
  • No, sorry that was the fault of my poor example. In my actual code I do put self in the manager. Should I put up my actual code, will that help? – innospark Mar 31 '13 at 06:24