Django QuerySet filter over string

14,863

Instead of

MyModel.objects.filter(car="old")

do

MyModel.objects.filter(car__icontains="old")

This will tell Django to filter out all MyModel objects where car fields contains old.

NB: You can also use car__contains="old" directly if you want a case sensitive search.

P.S. You should definitely check the PEP8 Python convention. This will help you to write code that is easy to read for Python developers.

Share:
14,863
Admin
Author by

Admin

Updated on December 01, 2022

Comments

  • Admin
    Admin over 1 year

    I have a models.py file with some rows and I would like to return on my HTML template all rows corresponding to my filter QuerySet.

    #models.py
    
    def Test(request) :
    
        CarCollection = MyModel.objects.filter(car="old")
    
        context = {
            "CarCollection" : CarCollection
        }
    
        return render(request, 'car.html', context)
    

    My html template looks like :

    <!-- car.html -->
    
    {% block content %} 
    <ul>
    {% for car in CarCollection %}
      <li>{{ car }}</li>
    {% endfor %}
    </ul>
    
    {% endblock %}
    

    But my objects looks like :

    Volvo_old_car
    Audi_old_car
    Nissan_new_car
    old_Bentley
    

    So I would like to isolate a string in my object (old for example) and return all objects with this string. But this string could be at the beginning, at the middle or at the end.

    The filter will return :

    Volvo_old_car
    Audi_old_car
    old_bentley
    

    I need to use Regex to do that ?

    Thank you by advance

  • Admin
    Admin over 7 years
    Thank you very much, I didn't know this option !