I have a django model:
class ActivationCode(models.Model):
id = models.FloatField(primary_key=True)
user = models.ForeignKey('User', to_field='id', on_delete=models.CASCADE)
I was having a hard time selecting an ActivationCode instance, so I tried to get the instance using its own id:
activation_codes = ActivationCode.objects.all()
print len(tuple(activation_codes))
>>> 1
for code in activation_codes:
cid = code.id
ActivationCode.objects.get(id=cid)
>>> DoesNotExist: ActivationCode matching query does not exist.
What’s going on? Why does it say the object doesn’t exist when I’m using its own id? How come I can get the instance using .all() but not .get()?
It might be worth noting that the above code is running in a class-based view in a test environment (TestCase). When I try the same thing in the terminal, it works fine.
Floats as primary keys are a Bad Idea.
You cannot guarantee the float representation is exactly the same on all levels. Python float implementation is interpreter-specific and likely differs in precision from your DB doubles.