Skip to content

Instantly share code, notes, and snippets.

@EnriqueSoria
Created December 5, 2023 14:03
Show Gist options
  • Save EnriqueSoria/41600067007c9778d5295a8fafc2ab05 to your computer and use it in GitHub Desktop.
Save EnriqueSoria/41600067007c9778d5295a8fafc2ab05 to your computer and use it in GitHub Desktop.
Utility to serialize generic model instances
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