28π
β
You canβt do this. filter
works at the database level, and the database doesnβt know anything about your long names. If you want to do filtering on a value, you need to store that value in the database.
An alternative is to translate the value back into the code, and filter on that:
country_reverse = dict((v, k) for k, v in COUNTRY_CHOICES)
Country.objects.filter(code=country_reverse['france'])
π€Daniel Roseman
3π
You can use Choices
from model_utils import Choices
class Country(models.Model):
COUNTRY_CHOICES = Choices((
('FR', _(u'France')),
('VE', _(u'Venezuela')),
))
code = models.CharField(max_length=2, choices=COUNTRY_CHOICES)
And make a query:
Country.objects.filter(code=Country.COUNTRY_CHOICES.france)
π€Danil
1π
You can swap values in constructor:
class PostFilter(django_filters.FilterSet):
def __init__(self, data=None, queryset=None, prefix=None, strict=None):
data = dict(data)
if data.get('type'):
data['type'] = Post.get_type_id(data['type'][0])
super(PostFilter, self).__init__(data, queryset, prefix, strict)
class Meta:
model = Post
fields = ['type']
π€radeklos
- Cannot connect to localhost API from Android app
- Using Django's built in web server in a production environment
- Installed Virtualenv and activating virtualenv doesn't work
0π
Inspired from this answer, I did the following:
search_for = 'abc'
results = (
[
x for x, y in enumerate(COUNTRY_CHOICES, start=1)
if search_for.lower() in y[1].lower()
]
)
Country.objects.filter(code__in=results)
π€raratiru
- Can I create model in Django without automatic ID?
- Django β filtering by "certain value or None"
- PyDev and Django: how to restart dev server?
- "Returning to that page might cause any action you took to be repeated" β Django
- Indirect inline in Django admin
Source:stackexchange.com