views:

33

answers:

2

I have a model with four fields that all have null=True defined. I'd like to prevent creation of an entirely null model; I'd rather not use a form validator since I want this to work with the default admin.

If I override the save() method to do a check, what do I raise on an error?

+1  A: 

You can raise anything really, it's up to you. In this case ValueError might be fitting.

googletorp
ValueError might be fitting, but could also be raised for other reason. Creating a custom error would allow him to only catch for the specific error he's looking to catch.
sheats
I agree that creating your own exception would be a better idea. Creating an exception called `NullModelError` or something equally descriptive would allow for specific exception catching.
jathanism
+1  A: 

I would put it in the save() method. Then, create a custom error that you can try/catch everywhere you call save on that model.

class EmptyModelDetected(Exception):
    pass

# Then in your save method
def save(self, *args, **kwargs):
    if self.field1 or self.field2 or self.field3 or self.field4:
        super(Model, self).save(*args, **kwargs)
    else:
        raise EmptyModelDetected()

# Then, wherever you call save
try:
    m.save()
except EmptyModelDetected:
    # handle the error
sheats