使用查询获取 views.py 中的 MultiSelectField 选定项目

Getting MultiSelectField selected items in views.py with query

我正在 views.py 中编写一个方法,该方法应该 return 按国家和流派划分的艺术家对象列表。

我在 models.py 中有此代码:

GENRES = ((1, 'Alternative'),
          (2, 'Blues'),
          (3, 'Classical'),
          (4, 'Country'),
          (5, 'Disco'),
          (6, 'Drum and Bass'),
          (7, 'Dubstep'),
          (8, 'EDM'),
          (9, 'Electronic'),
          (10, 'Experimental'),
          (11, 'Folk'),
          (12, 'Funk'),
          (13, 'Garage'),
          (14, 'Grime'),
          (15, 'Hardstyle'),
          (16, 'Heavy Metal'),
          (17, 'Hip Hop'),
          (18, 'House'),
          (19, 'Indie'),
          (20, 'Jazz'),
          (21, 'Multi-Genre'),
          (22, 'Pop'),
          (23, 'Punk'),
          (24, 'R&B'),
          (25, 'Reggae'),
          (26, 'Rock'),
          (27, 'Ska'),
          (28, 'Soul'),
          (29, 'Techno'),
          (30, 'Trance'),
          (31, 'Urban'),
          (32, 'World'))

genres = MultiSelectField(choices=GENRES, null=True)
country = CountryField(default="Poland")

目前我正在遍历所有对象并使用 python 搜索我需要的对象:

countries_selection = request.POST.get('countriesSelection')
genres_selection = request.POST.get('genresSelection')

results = []

artists = Artist.objects.all()
for artist in artists:
    if artist.country.name == countries_selection:
        if artist.genres:
            for genre in artist.genres.__str__().split(","):
                if genres_selection in genre:
                    results.append(artist)
        else:
            results.append(artist)

显然这不是一个好方法。我想通过使用查询获得相同的结果。我试过了:

Artist.objects.filter(genres__contains = 'Rock')

但它不会 return 任何东西,因为只有键保存在数据库中,而不是值。例如这个查询有效,但我的 views.py 函数中没有密钥:

Artist.objects.filter(genres__contains = '26')

这不是一个坏方法;如果您协助使用 multi-select 字段,这实际上是配置您尝试执行的操作的最佳方式。否则,我会建议在这种类型的实例中使用 manytomany 字段。允许更容易引用。 (仅供参考:Multiselect 只是将 ('25', 'genre') 保存为逗号分隔的字符串。这就是为什么您的方法在这种情况下最好)