Created
July 1, 2022 03:08
-
-
Save solancer/352fa245631394e0e9014bff1e89e70f to your computer and use it in GitHub Desktop.
Django / Python Entity or ID Pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def my_fun(user_or_id: UserOrId): | |
user = get_user(user_or_id) | |
# Do something with user | |
# These both do the same thing (but the first avoids the extra db hit) | |
my_fun(user) | |
my_fun(user.id) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import cast, overload | |
from uuid import UUID | |
@overload | |
def get_user(user_or_id: User) -> User: | |
... | |
@overload | |
def get_user(user_or_id: UUID) -> User: | |
... | |
UserOrId = User | UUID | |
def get_user(user_or_id): | |
if isinstance(user_or_id, User): | |
return user_or_id | |
return cast(User, User.objects.get(id=user_or_id)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment