S
S
sergey199408082017-05-21 08:40:20
Django
sergey19940808, 2017-05-21 08:40:20

Django how to do a simple attribute search?

View:

def search_foto(request):
        title = 'Поиск'

        try:
            query = request.GET['query']
            posts = OurFoto.objects.filter(name__startswith=query) | \
                OurFoto.objects.filter(text__startswith=query) or \
                OurFoto.objects.filter(date_added__startswith=query)
            context = {'title': title, 'posts': posts, 'query': query}
            return render(request, 'repository_our_fotos/search_form.html', context)

        except KeyError:
            return render(request, 'repository_our_fotos/search_form.html')

Why, when all attributes match, it produces the correct result, and when the first 2 are correct, and the last one is not correct, it produces other results? How to write a view to implement this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Eugene, 2017-05-21
@sergey19940808

You have the wrong code. There is also excellent native Django documentation, a lot of additional materials, books. Why trial and error?
To write correctly:

OurFoto.objects.filter(Q(name__startswith=query) | Q(text__startswith=query) | 
Q(date_added__startswith=query))

However, there are still several problems in the code:
  • it is better to switch to Class Based Views and Generic Views - the code will be simpler and will not need to be rewritten in the next versions of Django (view-functions are already kind of deprecated)
  • D
    Dmitry Tiunov, 2017-05-21
    @Dizast

    https://docs.djangoproject.com/en/1.11/topics/db/q...
    For queries with the OR operator, you need to use Q object.

    from django.db.models import Q
    
    
    posts = OurFoto.objects.filter(
        Q(name__startswith=query) | Q(text__startswith=query) | Q(date_added__startswith=query)
    )

    Didn't find what you were looking for?

    Ask your question

    Ask a Question

    731 491 924 answers to any question