Andro Andro - 7 days ago 8
Python Question

Django QuerySet filter over string

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

Answer

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.

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

Comments