Arda Soylu
Arda Soylu

Reputation: 13

django filtering a model that contains integer

models.py

STORY_CHOICES = (
    (0, 'Computer engineering'),
    (1, 'Mechanical engineering')
    )

views.py

story_list = MyOBJ.objects.all()
query = request.GET.get('q')
if query:
       story_list = story_list.filter(
           Q(story__icontains=query)
       ).distinct()

story takes data from STORY_CHOICES, when I try to search and write 'Computer engineering' it gives nothing. Also '0' is giving 'Computer engineering'. I want to cover it to text and take it string search. I try to take directly STORY_CHOICES and I met this fail: FieldError at /... Cannot resolve keyword 'STORY_CHOICES' into field. Choices are: .... I didn't find a true way.

Upvotes: 1

Views: 2027

Answers (1)

user8060120
user8060120

Reputation:

you can try:

in_filter = []
query = request.GET.get('q', '').lower()
for k, v in MyOBJ().STORY_CHOICES:
    if query in v.lower():
        in_filter.append(k)
if query:
    story_list = story_list.filter(
        Q(story__in=in_filter)
    ).distinct()

Upvotes: 2

Related Questions