Last active
March 25, 2022 05:56
-
-
Save abersheeran/082f1c1e11680801248136949b4bf1a8 to your computer and use it in GitHub Desktop.
A new idea of serializing Django model. https://aber.sh/articles/A-new-idea-of-serializing-Django-model/
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 Any, Dict, List | |
from django.core.exceptions import FieldDoesNotExist | |
from django.db import models | |
def serialize_model(model: models.Model) -> Dict[str, Any]: | |
result = { | |
name: serialize_model(foreign_key) | |
for name, foreign_key in model.__dict__["_state"].__dict__.get("fields_cache", {}).items() | |
} | |
for name, value in model.__dict__.items(): | |
try: | |
model._meta.get_field(name) | |
except FieldDoesNotExist: | |
continue | |
else: | |
result[name] = value | |
for name, queryset in model.__dict__.get("_prefetched_objects_cache", {}).items(): | |
result[name] = serialize_queryset(queryset) | |
return result | |
def serialize_queryset(queryset: models.QuerySet) -> List[Dict[str, Any]]: | |
return [serialize_model(model) for model in queryset] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment