AngelQuesada
AngelQuesada

Reputation: 431

objects.filter to get if string is contained in one or other field

I'm trying to filter my clients with a query. The user can look for the cif code and the client name writing in the same field so I can't know if he's looking for one thing or another. I'm trying to figure it out how to filter in both fields without excluding the other. I'll try give an example:

I have this on my client table:

[
    {
        "company_name":"Best Bar EUW",
        "cif":"ABCD1234"
    },
    {
        "company_name":"Word Bar EEUU",
        "cif":"POIU4321"
    },
    {
        "company_name":"Not a bad bar",
        "cif":"MNVB1321"
    }
]

Now I want to look for the "EE" string: the result that I want is the second object but the string "EE" is not included in the "cif" so it won't give me the result I want because it is included in one field but not in the other.

This is my Client model:

class Client(LogsMixin, models.Model):
    """Model definition for Client."""

    company_name = models.CharField("Nombre de la empresa", max_length=150, default="Nombre de empresa", null=False, blank=False)
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    cif = models.CharField("CIF", null=False, default="", max_length=50)
    platforms = models.ManyToManyField('consumptions.Platform', verbose_name=("Plataformas"))
    dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now)

What can I do with this?

Thanks in advance !

Upvotes: 0

Views: 457

Answers (1)

JPG
JPG

Reputation: 88499

Use logical OR with contains lookup

from django.db.models import Q

search_keyword = "EE"
or_expression = Q(company_name__contains=search_keyword) | Q(cif__contains=search_keyword)
Client.objects.filter(or_expression)

Upvotes: 2

Related Questions