Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django query with distinct and order_by

I have two models

class Employer(models.Model):
     name = models.CharField(max_length=300, blank=False)
     id = models.IntegerField()
     status = models.IntegerField()
     eminence = models.IntegerField(null=False,default=4)

class JobTitle(models.Model)
     name = models.CharField(max_length=300, blank=False)
     employer = models.ForeignKey(Employer,unique=False,null=True)
     activatedate = models.DateTimeField(default=datetime.datetime.now)

I need all employers in the order of whose jobtitle activated last.

Employer.objects.filter(status=1).order_by('eminence','-jobtitle__activatedate')

This query gives me what I want but it returns repeated employers if employer has more than one jobtitle.

I would use distinct() but in Django documents I found that

*Any fields used in an order_by() call are included in the SQL SELECT columns. This can sometimes lead to unexpected results when used in conjunction with distinct(). If you order by fields from a related model, those fields will be added to the selected columns and they may make otherwise duplicate rows appear to be distinct. Since the extra columns don't appear in the returned results (they are only there to support ordering), it sometimes looks like non-distinct results are being returned.*

Although they explained my problem no solution is specified.

Could give me a suggestion how can I group by my employer list without corrupting the API stability?

like image 205
brsbilgic Avatar asked Jul 11 '11 10:07

brsbilgic


1 Answers

You can place on the Employer class its latest JobTitle activation date, and then order by this field without using relations.[1] The tradeoff here is a bit of data duplication, and the necessity to update employer's latest job title activation date manually when corresponding JobTitle instance changes.

Also, check this post for another solution which uses annotate().

Related questions:

[1] Queryset API distinct() does not work?

like image 92
Anton Strogonoff Avatar answered Sep 23 '22 19:09

Anton Strogonoff