4

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

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, I didn't know this option !
1

You can use field lookups provided by Django to filter your queryset.

Django - Field lookups

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

Comments

0

You can use: endswith or istartswith in query.

CarCollection = MyModel.objects.filter(car__istartswith="old")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.