简体   繁体   中英

Why is Django considering these 2 same querysets as different?

I have 2 Django models - DJs and Songs. I'm trying to get sets of all the songs with the same name for a particular DJ.

This is how I'm doing that

for dj in DJ.objects.all():
    song_group_list = []
    dj_song_list = Song.objects.filter(artist=dj)
    for song in dj_song_list:
        song_group = dj_song_list.filter(name=song.name).order_by('song_id')
        if len(song_group) > 1:
            if song_group not in song_group_list:
                song_group_list.append(song_group)
    for group in song_group_list:
        print group

This outputs 2 duplicate sets with the same queryset results.

[<Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>]
[<Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>, <Song: Wake Up>] 

Why is the not in not able to distinguish between these 2 querysets?

Looking at Queryset 's source code I couldn't find any __eq__ method, so that is why when you're comparing two different instances of Queryset you're not finding any match.

>>> class A(object):
    pass

>>> A() == A()
False
>>> A() in [A()]
False

From docs :

If no __cmp__() , __eq__() or __ne__() operation is defined, class instances are compared by object identity (“address”).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM