I have a vector of three numbers as a name for a model.
i.e. 12-1-120 12-1-139 12-1-9 etc.
I wanted to sort instances of the model in descending order, using Django to display 12-1-139, 12-1-120, 12-1-9.
Except it always acts like a string, hence displaying 12-1-9, 12-1-139, 12-1-120.
I’ve tried using the ‘CommaSeparatedIntegerField’ yet it’s totally useless and still acts the same way.
The only way that I know of, that would technically work, is by having three separate “IntegerField”s and ordering it by the combination, which I think is too impractical.
Any pointers, or am I stuck with this impractical method?
I forgot to mention that I also needed to sometimes call this object using a string and I didn’t want to constantly convert the string to an int so I did it the other way around and stored the bunch of ints into a string using somewhat of a calculated field.
Here’s my basic code:
class MyModelName(models.Model):
name = models.CharField(max_length=15)
x = models.IntegerField(max_length=200)
y = models.IntegerField(max_length=200)
z = models.IntegerField(max_length=200)
def save(self, *args, **kwargs):
self.name = '-'.join([str(self.x), str(self.y), str(self.z)])
super(MyModelName, self).save(*args, **kwargs)
class Meta:
ordering = ["-x","-y","-z"]
Three integer fields is the way to go.
If you want to name your objects that way, you could always add a unicode function to your model…
https://docs.djangoproject.com/en/dev/ref/models/instances/#unicode
get_or_create example:
custom get or create method