Skip to content

Instantly share code, notes, and snippets.

@solancer
Created July 1, 2022 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solancer/352fa245631394e0e9014bff1e89e70f to your computer and use it in GitHub Desktop.
Save solancer/352fa245631394e0e9014bff1e89e70f to your computer and use it in GitHub Desktop.
Django / Python Entity or ID Pattern
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)
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