Created
December 5, 2023 14:03
-
-
Save EnriqueSoria/41600067007c9778d5295a8fafc2ab05 to your computer and use it in GitHub Desktop.
Utility to serialize generic model instances
This file contains hidden or 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 __future__ import annotations | |
from typing import Any | |
from typing import NamedTuple | |
from django.contrib.contenttypes.models import ContentType | |
from django.db import models | |
class GenericModelInstance(NamedTuple): | |
"""Utility to avoid sending whole objects to Celery tasks.""" | |
content_type_id: int | |
model_id: Any | |
def get_instance(self) -> models.Model: | |
content_type = ContentType.objects.get_for_id(self.content_type_id) | |
return content_type.get_object_for_this_type(pk=self.model_id) | |
@classmethod | |
def from_instance(cls, instance: models.Model) -> GenericModelInstance: | |
content_type = ContentType.objects.get_for_model(instance, for_concrete_model=True) | |
return cls( | |
content_type_id=content_type.pk, | |
model_id=instance.pk, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment