Django:在 TextChoices class 上按较不详细(数据库名称)过滤

Django: Filter by less verbose (database name) on TextChoices class

我有一个模型:

class RegulationModel(models.Model):

    class Markets(models.TextChoices):
        EUROPE = 'E', 'Europe'
        US = 'US', 'US'
        JAPAN = 'J', 'Japan'
        KOREA = 'K', 'Korea'
        BRAZIL = 'B', 'Brazil'
        INDIA = 'I', 'India'
        CHINA = 'C', 'China'

    market = models.CharField(verbose_name='Market:', max_length=2, choices=Markets.choices)
    [... more fields ..]

如何过滤 Markets class 中更详细的选择?

例如我想用“中国”过滤,我想做这样的事情:

regulation = RegulationModel.objects.get(market__verbose='China')

(我知道这是不可能的,但这只是一个想法)

我这样做的原因是因为我从 AJAX 获得选择,因此格式不是 ["C","US"] 等

我能够通过以下方式将详细信息转换为数据库值:

>> market = 'China'
>> market_db = {y:x for x, y in RegulationModel.Markets._value2label_map_.items()}[market]
>> market_db
'C'

然后我可以用它来查询,但它看起来不是很pythonic。

我相信你可以做到以下几点:

china_code = list(filter(lambda x: x[1] == 'China', RegulationModel.Market.choices)).pop()[1]
regulation = RegulationModel.objects.get(market=china_code)

但这有点老套。我建议使用 django-useful 及其 Choices 的实现。