Django F() Objects And Custom Saves Weirdness
I've been working with Django F() objects to update my models, in order to avoid race conditions. I also have a custom save method for my model (I want rebels to range from 0 to 10
Solution 1:
When comparing different types in Python, numbers always are sorted before other objects. Thus, 100
is always going to be lower than the F()
object.
You'll indeed need to special-case testing for this; you could instead test if self.rebels
is an instance of F
:
def save(self, *args, **kwargs):
...
if not isinstance(self.rebels, F):
if self.rebels > 100:
self.rebels = 100
elif self.rebels < 0:
self.rebels = 0
...
super(World, self).save(*args, **kwargs)
Python 2 does this to support sorting lists of mixed types, while guaranteeing a stable sort order at the same time.
Because this behaviour could lead to subtle unexpected bugs (exactly like in your case), this behaviour has been removed in Python 3, and only types that support comparisons explicitly are supported.
Post a Comment for "Django F() Objects And Custom Saves Weirdness"