[Answered ]-Django F() objects and custom saves weirdness

2👍

✅

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.

Leave a comment