ormar icon indicating copy to clipboard operation
ormar copied to clipboard

Allow filtering by foreign keys fields

Open Abdeldjalil-H opened this issue 2 years ago • 1 comments

  Let's say we have two tables
class Author:
    id = ormar.Integer(primary_key=True)
class Book
    ...
    author = ormar.ForeignKey(Author)

Then the following queries should be equivalent

Book.objects.get(author=5)

Book.objects.get(Book.author==5)

However the second query raises the following exception

AttributeError: Cannot filter by Model, you need to provide model name

This is caused by self._check_field() inside the method FieldAccessor._select_operator. An alternative approach is to replace the last query by

Book.objects.get(Book.author.id==5)

but this will do a join query, which is different from the first query. My question is, why filtering by foreign keys fields is not allowed?

Originally posted by @Abdeldjalil-H in https://github.com/collerek/ormar/discussions/845

Abdeldjalil-H avatar Sep 23 '22 16:09 Abdeldjalil-H

Sorry for necro-posting but I got the same problem here, was it fixed in some way? Thanks.

CallMePixelMan avatar Jul 18 '23 12:07 CallMePixelMan