Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Select by foreign key doesn't works as expected #2304

Closed
penja opened this issue Nov 25, 2020 · 2 comments
Closed

Select by foreign key doesn't works as expected #2304

penja opened this issue Nov 25, 2020 · 2 comments

Comments

@penja
Copy link

penja commented Nov 25, 2020

Hello. We have the foreign keys with related field that is not equal the primary key to the related model.
The following code snippet shows an invalid SELECT query when we use in the select query related model object instead of just identifier.

from peewee import *

db = SqliteDatabase(':memory:')


class Base(Model):
    class Meta:
        database = db


class A(Base):
    id = AutoField()
    a_id = CharField(unique=True, max_length=24)


class B(Base):
    id = AutoField()
    a = ForeignKeyField(A, field="a_id")


db.create_tables([A, B])

a = A.create(a_id="example")
b = B.create(a=a)
print(B.select().where(B.a == b.a).sql())
print(B.select().where(B.a == b.a_id).sql())

Output:

('SELECT "t1"."id", "t1"."a_id" FROM "b" AS "t1" WHERE ("t1"."a_id" = ?)', [1])
('SELECT "t1"."id", "t1"."a_id" FROM "b" AS "t1" WHERE ("t1"."a_id" = ?)', ['example'])

Thanks

@coleifer
Copy link
Owner

Thanks for the succinct issue report. For now I've made a provisional fix which correctly delegates to the ForeignKeyField.db_value() method when a model instance is converted. The fix is not perfect since we still want a way to convert model instances when a converter is present (but is not able to handle the given model instance), so I am catching possible TypeError or ValueError. I believe this should work in practice and have put some new tests in place.

coleifer added a commit that referenced this issue Nov 25, 2020
…odels.

When a model instance is passed as a parameter on the right-hand-side of
an expression, Peewee would previously just grab the model's primary-key
value. This breaks queries where the left-hand-side is a foreign-key
that points to a field other than the primary-key.

To address this I've added a test to try and use the converter in the
scope (if available), and fall back to using the model pk.

Fixes #2304
@penja
Copy link
Author

penja commented Nov 25, 2020

Many thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants