我有2个Django模特 - DJ和歌曲。
class DJ(models.Model):
name = models.CharField(max_length=50, unique=True)
rank = models.IntegerField()
class Song(models.Model):
song_id = models.IntegerField()
name = models.CharField(max_length=150)
artist = models.ForeignKey(DJ, default=None, blank=True, null=True)
release = models.CharField(max_length=500, default=None, blank=True, null=True)
release_date = models.DateField()
duplicate = models.BooleanField(default=False)
我试图获取特定DJ的所有同名歌曲。
这就是我这样做的方式
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
这将输出具有相同查询集结果的重复集。
[<Song: Ping Pong>, <Song: Ping Pong>, <Song: Ping Pong>]
[<Song: Everybody Is In The Place>, <Song: Everybody Is In The Place>, <Song: Everybody Is In The Place>]
[<Song: Jumper>, <Song: Jumper>, <Song: Jumper>]
[<Song: Man With The Red Face>, <Song: Man With The Red Face>, <Song: Man With The Red Face>, <Song: Man With The Red Face>, <Song: Man With The Red Face>, <Song: Man With the Red Face>]
[<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>]
如何针对上述问题获取不同的查询集?
答案 0 :(得分:0)
我认为这个问题是因为append
方法,因为,首先你得到所有的os歌曲列表,然后将它附加到song_list
,所以你必须用有序列表替换当前列表:
所以请将您的代码更改为:
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 and (song_group not in song_group_list):
song_group_list=song_group
for group in song_group_list:
print group