Search code examples
djangodjango-modelsdjango-q

How to make Q queries with models with foreign keys?


my model is defined like this:

class Model2(models.Model):
    id = models.IntegerField(primary_key=True)
    name = ...

class Model1(models.Model):
    id = models.IntegerField(primary_key=True)
    model2 = models.ForeignKey(Model2, to_field='id', db_column='model2')

The problem is I do not know how to make OR queries with queryset.

qs = Model1.objects.filter(Q(model2.id__icontains=search) | Q(id__icontains=search))

I get

keyword can't be an expression

So the question is how can I reference to the field of the related model in Q queries? Thanks


Solution

  • This should work:

    qs = Model1.objects.filter(Q(model2__id=search) | Q(id=search))
    

    I would revisit the implementation if you are looking for id__icontains

    If you search for 1, then it would look for 1, 11, 121, 166..., (any id with 1 in it) which is probably not what you want.

    To specifically point out your error,

    Q(model2.id__icontains=search)
    

    should be

    Q(model2__id__icontains=search)