Tortoise-orm: Should a nullable ForeignKeyField return null even though it exists but just hasn't been fetched/prefetched?

Created on 13 Jan 2020  Â·  3Comments  Â·  Source: tortoise/tortoise-orm

Should a model instance nullable ForeignKeyField return null when it has not been fetched/prefetched? It feels counter intuitive to me, take the following example

class Task(BaseModel, TimestampMixin):
    mother_task = fields.ForeignKeyField('models.Task', null=True)

    def has_mother(self):
        if self.mother:
            return True
        return False
...
task1 = Task()
await task1.save()
task2 = Task(mother_task=task1)
await task2.save()
...
if task2.has_mother():
    #This never prints
    print('Task 2 has a mother')

If I set it to nullable, and it return null, then I expect that it doesn't exist.

In the end I had to resort to the following :

...
async def has_mother(self):
    if self.mother_id:
        return True
    return False

Is this the intended way to go by?

Waiting for feedback bug

All 3 comments

Ah, I get it.

Even though the self.mother is a lazy awaitable, (e.g. you do an if await self.mother it would work), it knows it's not null. So I should implement a __bool__ operator?

Then this will be slightly less confusing.

Thanks for bringing this to my attention :smile:

I release v0.15.8 with a fix for this, please test :smile:

Thank you it works

Was this page helpful?
0 / 5 - 0 ratings

Related issues

asyncins picture asyncins  Â·  4Comments

anindyamanna picture anindyamanna  Â·  6Comments

sylvoslee picture sylvoslee  Â·  7Comments

theblackturtle picture theblackturtle  Â·  5Comments

lntuition picture lntuition  Â·  4Comments