Sri Harsha
Sri Harsha

Reputation: 107

Remove duplicates in the query set

I have a query set like the one below which depicts the albums and songs associated with those albums. The model name is UserSongs

<QuerySet [{'id': 1, 'album': 'Sri', 'song': 'in the end','release': 2017},
{'id': 2, 'album': 'Adi', 'song': 'cafe mocha','release': 2016}, 
{'id': 3, 'album': 'Shr', 'song': 'smooth criminal','release': 2016}, 
{'id': 4, 'album': 'Mouse', 'song': 'trooper','release': 2017},
{'id': 5, 'album': 'Mouse', 'song': 'my mobile','release': 2015},
{'id': 6, 'album': 'Sri', 'song': 'my office','release': 2018},
{'id': 7, 'album': 'Sri', 'song': 'null','release': null},
{'id': 8, 'album': 'Mouse', 'song': 'null','release': null}]>

In the backend, I'm converting the query set into a list. See code below:

albums_songs = UserSongs.objects.filter(album__in = 
['Sri','Mouse']).values('albums','songs')
list_albums_songs = list(albums_songs)

I'm sending this list to the front-end for displaying it in table.Sri,Mouse have multiple entries since they have released multiple songs. In the front end, these songs are displayed in a table with album and songs as entries. Each item in the query set is displayed as one row. Like the one below.

Album   Songs
Sri     in the end
Adi     cafe mocha
Adi     null
Shr     smooth criminal
Mouse   trooper
Mouse   my mobile
Sri     my office 
Sri     null 
Mouse   null  

But in the table, null entry for the song is also displayed. I don't want to display that null entry for only Sri,Mouse. I want to diaplay the song=null doe Adi.I can remove it after converting into list and iterating over the list. But that is costly. I believe that we can do it in django query itself. Something like, if album is Sri or Mouse, then check for song = null and don't get that entry.

Or after getting the query set, before converting into list, can we remove those items from query set?

Upvotes: 1

Views: 52

Answers (1)

blhsing
blhsing

Reputation: 107124

You can use the isnull filter:

albums_songs = UserSongs.objects.filter(album__in=['Sri','Mouse'], songs__isnull=False).values('albums','songs')

EDIT: With the new requirements in your updated question, you should use the exclude method instead:

albums_songs = UserSongs.objects.exclude(album__in=['Sri','Mouse'], songs__isnull=True).values('albums','songs')

Upvotes: 2

Related Questions