B
B
bbquite2021-10-19 11:32:32
Django
bbquite, 2021-10-19 11:32:32

How to get the field by which the django object was found?

For example, there is a model:

class TestModel(models.Model):

    title = models.CharField()
    desc = models.CharField()
    other_field = models.CharField()


And I'm trying to find the object:
result = TestModel.objects.filter(Q(title__icontains='test') | Q(desc__icontains='test') | Q(other_field__icontains='test') )


Is it possible to find out the field by which this object was found?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-10-19
@WebDev921

The end goal is a little unclear. If you just look at the value of the object field - for some reason you can’t - then you can add what you want to the annotated fields:

.annotate(
    title_contains=Case(
        When(
           Q(title__icontains='test'),
           then=V('True')
        ),
       default=(V(False)),
       output_field=BooleanField()
    ),
    desc_contains=Case(
        When(
           Q(desc__icontains='test'),
           then=V('True')
        ),
       default=(V(False)),
       output_field=BooleanField()
    ),
...

and as a result, a boolean value will arrive in the title_contains, desc_contains, ...
fields - in which corresponding field the desired match was found
for obj in result:
   print(obj.title_contains) # триггернулось ли по title
   print(obj.desc_contains) # триггернулось ли по desc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question