ProgrammingError: when using order_by and distinct together in django

旧时模样 提交于 2019-12-10 11:09:55

问题


I have a model like below

class ProductScore(models.Model):
    client = models.ForeignKey(User)
    created = models.DateTimeField(default=datetime.datetime.now)
    score = models.IntegerField()
    scale = models.ForeignKey(Product) 

As of now i am using the below query to filter out the duplicates from the above model

scores = ProductScore.objects.filter(client=request.user).distinct('scale')

By the above query it was returning the unique results but are old(created date was very old), i mean for example if the above table ProductScore has 10 duplicate records in which 5 of them are created yesterday and 5 of them are created today, the above query is returning 5 unique records which are created yesterday.

But i want the records which are created mostly recently(i.e., today) and unique so i tried like below

scores = ProductScore.objects.filter(client=request.user).order_by('created').distinct('scale')

which was not working and throwing some programming error exception

*** ProgrammingError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions
LINE 1: SELECT DISTINCT ON ("product_productscore"."scale...
                            ^

So how can i get the most recently created unique records form the above table ?


回答1:


PostgreSQL is asking you to do this:

ProductScore.objects.filter(client=request.user).order_by('scale', '-created').distinct('scale')

...ordering by -created will give you the most recent of each duplicate, though your overall query results will be ordered by scale field



来源:https://stackoverflow.com/questions/24865235/programmingerror-when-using-order-by-and-distinct-together-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!