问题
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