Django distinct() not returning distinct values

瘦欲@ 提交于 2019-12-25 03:06:24

问题


I have a Session model like this:

class Session(models.Model):  
    user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name="sessions")
    flavor = models.ForeignKey(Flavor, null=True, blank=True, on_delete=models.CASCADE, related_name="sessions")
    ....

And I'm trying to run a query:

sessions = Session.objects.all().values('flavor__pk', 'user__pk').distinct()

But when I then print the sessions object I get this:

<QuerySet [{'user__pk': 14544, 'flavor__pk': 1}, {'user__pk': 14544, 'flavor__pk': 1}, {'user__pk': None, 'flavor__pk': 30}, {'user__pk': 193, 'flavor__pk': 30}, '...(remaining elements truncated)...']>

Which, if you look closely, the first two entries are exactly the same {'user__pk': 14544, 'flavor__pk': 1}! Isn't this supposed to be distinct?


回答1:


I think this code works:

Session.objects.all().values_list('flavor__pk', 'user__pk').distinct()


来源:https://stackoverflow.com/questions/52012652/django-distinct-not-returning-distinct-values

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