How to check the PK of a foreign-key relationship without loading the related model; how to compare two objects #1658
-
I have put my questions in the comments in the below code. I did not find answers in the documentation. class User(Model):
username = CharField(max_length=255, primary_key=True)
organization: ForeignKeyNullableRelation[Organization] = ForeignKeyField(
"models.Organization",
related_name="users",
on_delete=OnDelete.RESTRICT,
null=True,
)
@property
def is_admin(self):
# Does this load the organization model?
# Is there a way to check the foreign key itself for being null without loading the referenced model?
return self.organization is None
def may_create_user(self, user: "User_Pydantic"):
if self.is_admin:
return True
org = user.organization
if org is None:
return False
# Is this the correct way to compare two models?
# Does tortoise do original-object-return so that we can test using `is`?
return org == self.organization |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi @merlinz01. I know this is late, but in case you still didn't find an answer and for other poeple using Tortoise orm. @property
def is_admin(self):
return self.organization_id is None Same thing for your second question. |
Beta Was this translation helpful? Give feedback.
Hi @merlinz01. I know this is late, but in case you still didn't find an answer and for other poeple using Tortoise orm.
When you use a foreign key field called
fk_field
, tortoise will usefk_field_id
to store the value of the related model id. Thefk_field
is used to load the relation.For you're question,
is_admin
does not load theorganization
. You need to usefetch_related
to load it. But you can check if the foreign key is null without loading it. Here's how you can do it:Same thing for your second question.