Reputation: 35
I was programming a function in python that required a group of objects of a model to be ordered by a specific parameter (the codename of a problem), this parameter resulted to be a string. When I sorted it inside the Problems table, it worked correctly, however, when I sorted it inside ProblemUser model (using order_by) the sort was completely incorrect respecting the real results.
I managed to work it around by sorting the elements AFTER i got it from the model using sorted() function, however, i am still with the doubt on how to sort a foreign key in the order_by function.
class Problem(models.Model):
problem_name = models.CharField(max_length=256,default='Unnamed')
source = models.CharField(max_length=200)
url = models.CharField(max_length=200)
codename = models.CharField(max_length=200, primary_key=True)
difficulty = models.CharField(max_length=32,default='UNRATED')
class ProblemUser(models.Model):
problem = models.ForeignKey(Problem)
handler = models.ForeignKey(Handler)
solved = models.BooleanField(default=True)
voted = models.BooleanField(default=False)
entry = models.DateField()
t = ProblemUser.objects.filter(solved=1, handler=Handler.objects.get(id=1)).order_by('problem')
t[0].problem.codename < t[42].problem.codename
False
t[1].problem.codename < t[42].problem.codename
True
I also tried order_by('problem__codename')
Some codenames examples are (these are outputs that i remember to have seen when i ordered by the foreign key):
S_1_T
S_1000_E
S_1001_F
.
.
.
S_2_P
Thank you for your time and help! :).
Upvotes: 1
Views: 3755
Reputation: 508
try it like that please.
t = ProblemUser.objects.filter(solved=1, handler=Handler.objects.get(id=1)).order_by('problem__codename')
Upvotes: 1