question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unable to use .save() method on a nullable ForeignKeyField

See original GitHub issue

About the bug Returns wrong value when trying to save FK field, which may be null

To Reproduce

import asyncio
import logging

from tortoise import Tortoise, fields, models

logging.basicConfig(level=logging.DEBUG)

POSTGRES_URL = "postgres://postgres:postgres@localhost/postgres"


class ModelA(models.Model):
    string = fields.TextField(default="")


class ModelB(models.Model):
    a_model = fields.ForeignKeyField(
        "models.ModelA", related_name="b_models", null=True
    )


async def main():
    await Tortoise.init(db_url=POSTGRES_URL, modules={"models": ["__main__"]})
    await Tortoise.generate_schemas()

    a, _ = await ModelA.get_or_create()
    b, _ = await ModelB.get_or_create()

    b.a_model = a
    await b.save()

    await Tortoise.close_connections()


asyncio.run(main())

This code uses None as a_model_id on update query. But if there is .create or .get_or_create method with passed a_model arg, then the code uses the right values.

Expected behavior .save method should use the right values when updating nullable foreign key.

Additional context Python version: CPython 3.7.4 Installed packages: aiosqlite==0.10.0 asyncpg==0.18.3 atlastk==0.10.7 ciso8601==2.1.1 PyPika==0.35.4 tortoise-orm==0.13.3

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:8 (8 by maintainers)

github_iconTop GitHub Comments

2reactions
nsidnevcommented, Sep 5, 2019

By the way, your bug reports are really good I’m a big fan!

Thanks! 😄 I’m glad that this project exists and I am happy to help it this way, at least until I haven’t enough knowledge to open the PR with fix.

1reaction
nsidnevcommented, Sep 6, 2019

FYI, the partial/property change is only in the models file here: tortoise/tortoise-orm/pull/185/files#diff-2b3e042db0b773b93d8a98880434ee35

Thank you, I’ll watch it.

Just checked on my project. It worked as it should, thanks for the quick fix!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Django error while saving Foreign Key - Can not assign none ...
Irrespective of null=True/False, value is being set from save method and saved. I am getting this error in View File. form = EventsForm(request....
Read more >
Null constraint violations when saving objects with ForeignKey ...
instB.save() # fails with IntegrityError: null value in column "a_id" ... def prepare_object(obj): # helper method to work around django
Read more >
ForeignKey - ormar
This method will not work on ManyToMany relations - there, both sides of the relation have to be saved before adding to relation....
Read more >
ModelForm regression when setting None into a ForeignKey
It appears that when using a ModelForm to "unset" a non-required foreign key field, Django 1.8 no longer will set the foreign key...
Read more >
Django Tutorial Part 3: Using models - Learn web development
Model , and can include fields, methods and metadata. ... You have to call save() to store modified values to the database.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found