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

Cannot reset ForeignKeyField to None #2428

Closed
orsinium opened this issue Jun 11, 2021 · 2 comments
Closed

Cannot reset ForeignKeyField to None #2428

orsinium opened this issue Jun 11, 2021 · 2 comments

Comments

@orsinium
Copy link

orsinium commented Jun 11, 2021

import peewee

class A(peewee.Model):
    pass

class B(peewee.Model):
    a = peewee.ForeignKeyField(A, null=True)

b = B(a=A())

# works as expected:
b.a
# <A: None>

# unexpected:
b.a = None
b.a
# <A: None>

Expected behavior: when None is assigned to the ForeignKeyField, the field value is None.
Actual behavior: assigning None to the ForeignKeyField has no effect.

How to reset a foreign key to None?

@coleifer
Copy link
Owner

This was happening because peewee only cleared the related object reference (the A instance on B) if the actual value of the FK changed. Since it was NULL to start with (e.g. A.id is None), peewee did not register that there was anything to do. In practice I don't believe this would lead to any inconsistency in the database, but I can see how it might be confusing.

Fixed.

@orsinium
Copy link
Author

Thank you for the answer! I think I understand now: setting b.a to None was interpreted as setting b.a.id to None, which is already true. In my application, I distinguish between "the A record is not created yet" and "there is no A record related to this B record". So you're right, it was confusing. I found a workaround, though, by implementing A.__bool__.

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