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

Insert operations of models with non-PK foreign keys fail when passing a target object instance #2408

Closed

Conversation

smuething
Copy link

I have a model A with a ForeignKeyField column that uses the field parameter to set a non-pk reference column in the target model:

class Target(Model):
    key = FixedCharField(8,unique=True)

class A(Model):
    target = ForeignKeyField(Target,field="key",lazy_load=False)

When trying to create instances of A, I can do so with create(), but not with the ModelInsert-based methods:

t = Target.create(key="X")

A.create(target=t) # works

A.insert(target="X").execute() # works
A.insert(target=t).execute()   # fails

In the last case, the generated SQL uses the primary key of t instead of t.key because the code path in ModelInsert does not apply the field parameter of the ForeignKeyField to the passed-in model instance. The attached patch fixes the problem for me.

If a model specifies a ForeignKeyField with a target field that is not the primary key,
model inserts fail if the value passed for the foreign key column is an object of the
target model, because the code currently always uses the pk column of the target object
in the SQL statement.

This patch fixes the problem by always applying the column converter of ForeignKeyField
columns to the passed-in value.
@coleifer coleifer closed this in 2f4535f May 11, 2021
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

Successfully merging this pull request may close these issues.

1 participant