INSERT or UPDATE in django's save() method
tech.karolzielinski.com
tech.karolzielinski.com
(This approach would cause problems with funny black magic triggers but funny black magic triggers cause problems anyway)
It's been reported before and they consciously chose the current behavior. I don't agree with their decision, but it is something they're aware of.
EDIT: There is a way to subclass models.Model and not have it be an abstract or real model (I don't remember at the moment) and you could, in that subclass, do a force_insert or force_update based on the PK status so that everything in your project inheriting from that subclass would have that behavior.
basically:
def save(self, *args, **kwargs):
if self.pk:
kwargs['force_update'] = True
kwargs['force_insert'] = False
else:
kwargs['force_insert'] = True
kwargs['force_update'] = False
super(MyModelBase, self).save(*args, **kwargs)
So, one can modify that behavior if they want to without having to patch too much - maybe someone can comment on subclassing models.Model while not having Django consider it a model (I think I got it from the Pro Django book if someone has it available).EDIT2: modified the code to make sure that force_insert and force_update couldn't both be True.
class AlwaysUpdate(object):
def save(self, *args, **kwargs):
if self.pk:
kwargs['force_update'] = True
kwargs['force_insert'] = False
else:
kwargs['force_insert'] = True
kwargs['force_update'] = False
return super(AlwaysUpdate, self).save(*args, **kwargs)
class MyModel(AlwaysUpdate, models.Model):
pass # model def here def save(self, *args, **kwargs):
if not self.pk:
pass # new object
else:
pass # old object
return super(MyObject, self).save(*args, **kwargs)