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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With