Get distinct values of Queryset by field

后端 未结 3 403
再見小時候
再見小時候 2020-12-13 03:42

I\'ve got this model:

class Visit(models.Model):
    timestamp  = models.DateTimeField(editable=False)
    ip_address = models.IPAddressField(editable=False)         


        
相关标签:
3条回答
  • 2020-12-13 04:04

    With Alex Answer I also have the n:1 for each item. Even with a distinct() clause.

    It's weird because this is returning the good numbers of items :

    Visit.objects.filter(stuff).values("ip_address").distinct().count()
    

    But when I iterate over "Visit.objects.filter(stuff).values("ip_address").distinct()" I got much more items and some duplicates...

    EDIT :

    The filter clause was causing me troubles. I was filtering with another table field and a SQL JOIN was made that was breaking the distinct stuff. I used this hint to see the query that was really used :

    q=Visit.objects.filter(myothertable__field=x).values("ip_address").distinct().count()
    print q.query
    

    I then reverted the class on witch I was making the query and the filter to have a join that doesn't rely on any "Visit" id.

    hope this helps

    0 讨论(0)
  • 2020-12-13 04:10

    The question is different from what the title suggests. If you want set-like behavior from the database, you need something like this.

    x = Visit.objects.all().values_list('ip_address', flat=True).distinct()
    

    It should give you something like this for x.

    [1.2.3.4, 2.3.4.5, ...]
    

    Where

    len(x) == len(set(x))
    

    Returns True

    0 讨论(0)
  • 2020-12-13 04:26

    What you want is:

    Visit.objects.filter(stuff).values("ip_address").annotate(n=models.Count("pk"))
    

    What this does is get all ip_addresses and then it gets the count of primary keys (aka number of rows) for each ip address.

    0 讨论(0)
提交回复
热议问题