Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering objects based on two attributes being the same

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")]
 

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading