I have a model:
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 ..]
How do I filter on the more verbose choice in the Markets
class?
For example say I want to filter with "China", i'd like to do something like:
regulation = RegulationModel.objects.get(market__verbose='China')
(I know this isn't possible but it's just to get an idea)
The reason why I am doing this is because I am getting the choice from AJAX therefore the format is not ["C","US"] .etc.
I was able to convert the verbose to the database value via:
>> market = 'China'
>> market_db = {y:x for x, y in RegulationModel.Markets._value2label_map_.items()}[market]
>> market_db
'C'
And then I could use this to query but it doesn't seem very pythonic.
CodePudding user response:
I believe you can do following:
china_code = list(filter(lambda x: x[1] == 'China', RegulationModel.Market.choices)).pop()[1]
regulation = RegulationModel.objects.get(market=china_code)
But it is a bit hacky. I recommend using django-useful and its implementation of Choices.