mirror of
https://github.com/carrotquest/django-clickhouse.git
synced 2024-11-22 00:56:37 +03:00
Moved model_to_dict to utils
This commit is contained in:
parent
d300d6e46e
commit
ce1a206b04
|
@ -1,5 +1,6 @@
|
|||
from django.db.models import Model as DjangoModel
|
||||
from django.forms import model_to_dict
|
||||
|
||||
from django_clickhouse.utils import model_to_dict
|
||||
|
||||
|
||||
class Django2ClickHouseModelSerializer:
|
||||
|
@ -13,13 +14,7 @@ class Django2ClickHouseModelSerializer:
|
|||
self.exclude_serialize_fields = exclude_fields
|
||||
|
||||
def serialize(self, obj): # type: (DjangoModel) -> 'ClickHouseModel'
|
||||
# Standard model_to_dict ignores some fields if they have invalid naming
|
||||
data = {}
|
||||
sync_fields = set(self.serialize_fields) - set(self.exclude_serialize_fields or ())
|
||||
for name in sync_fields:
|
||||
val = getattr(obj, name, None)
|
||||
if val is not None:
|
||||
data[name] = val
|
||||
data = model_to_dict(obj, fields=self.serialize_fields, exclude_fields=self.exclude_serialize_fields)
|
||||
|
||||
# Remove None values, they should be initialized as defaults
|
||||
params = {}
|
||||
|
|
|
@ -1,10 +1,12 @@
|
|||
import datetime
|
||||
from typing import Union, Any, Optional, TypeVar, Set
|
||||
from itertools import chain
|
||||
from typing import Union, Any, Optional, TypeVar, Set, Dict, Iterable
|
||||
|
||||
import pytz
|
||||
import six
|
||||
from importlib import import_module
|
||||
from importlib.util import find_spec
|
||||
from django.db.models import Model as DjangoModel
|
||||
|
||||
from .database import connections
|
||||
|
||||
|
@ -96,4 +98,26 @@ def get_subclasses(cls, recursive=False): # type: (T, bool) -> Set[T]
|
|||
for subcls in subclasses.copy():
|
||||
subclasses.update(get_subclasses(subcls, recursive=True))
|
||||
|
||||
return subclasses
|
||||
return subclasses
|
||||
|
||||
|
||||
def model_to_dict(instance, fields=None, exclude_fields=None):
|
||||
# type: (DjangoModel, Optional[Iterable[str]], Optional[Iterable[str]]) -> Dict[str, Any]
|
||||
"""
|
||||
Standard model_to_dict ignores some fields if they have invalid naming
|
||||
:param instance: Object to convert to dictionary
|
||||
:param fields: Field list to extract from instance
|
||||
:param exclude_fields: Filed list to exclude from extraction
|
||||
:return: Serialized dictionary
|
||||
"""
|
||||
data = {}
|
||||
|
||||
opts = instance._meta
|
||||
fields = fields or {f.name for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many)}
|
||||
|
||||
for name in set(fields) - set(exclude_fields or set()):
|
||||
val = getattr(instance, name, None)
|
||||
if val is not None:
|
||||
data[name] = val
|
||||
|
||||
return data
|
||||
|
|
Loading…
Reference in New Issue
Block a user