nesalexy
nesalexy

Reputation: 878

Django. How i can get list of Users with a duplicate?

i have array like this: [1, 1, 1, 2, 3]. How i can get users with a duplicate? For example this query return list without duplicate

list=     User.objects.filter(id__in=[1, 1, 1, 2, 3])

for example it will be users with id's:

1,
2,
3

but i need list of users like this:

    1,
1,
1,
    2,
    3

Upvotes: 1

Views: 301

Answers (2)

nigel222
nigel222

Reputation: 8212

Get your queryset sorted in the right order. .order_by('id) for ascending by id (which may be the default anyway). Then iterate over the queryset with code to make extra operations with the same object (or a copy thereof) as dictated by the list of IDs.

idlist = [1, 1, 1, 2, 3]  
queryset = User.objects.filter(id__in = idlist ).order_by('id')      

for object in queryset:
    for _ in range( idlist.count( object.id))
        do_something_with( object)

Note, this is only one DB call (one queryset), unlike the accepted answer which does one DB query for each element in the id list. Not good.

Upvotes: 1

Jay
Jay

Reputation: 1309

list = []
for x in [1, 1, 1, 2, 3]:
    list.append(User.objects.filter(id=x)

It this what you mean? I don't quite understand the spacing.

Upvotes: 1

Related Questions