With regards to the below model, how could I filter through existing objects so that I find only objects where 'Name' contains a certain word, for example, "Green" but also where the vendor of the object may contain "Green"? I am of course referring to the value (assuming same type although in this example I am using char and text field).
class Hat(models.Model):
Name = models.CharField(max_length=255, unique = False)
Size = models.IntegerField(choices=list(zip(range(1, 11), range(1, 11))), unique=False)
Vendor = models.TextField(max_length=255, unique = False)
List = [for Hat in Hat.objects.filter(Name__contain="Green")]
CodePudding user response:
You can .filter(…)
[Django-doc] with:
from django.db.models import Q
Hat.objects.filter(Name__contains='Green', Vendor__contains='Green', _connector=Q.OR)
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be:
vendor
instead of.Vendor
Note: For case-insensitive matches, you can use the
__icontains
lookup [Django-doc]. Case insitive matching is not equivalent to converting the two operands to lowercase: case insensitive matching is more sophisticated since some characters have no uppercase or lowercase variant, and there are certain rules when two characters are considered the same in an case-insenstive manner.