2016-09-18 02:29:00 +03:00
|
|
|
import inspect
|
2016-09-18 03:09:56 +03:00
|
|
|
|
2016-09-18 02:29:00 +03:00
|
|
|
from django.db import models
|
|
|
|
from django.db.models.manager import Manager
|
|
|
|
|
2016-09-18 03:09:56 +03:00
|
|
|
|
2017-06-26 17:31:34 +03:00
|
|
|
try:
|
|
|
|
import django_filters # noqa
|
2018-07-20 02:51:33 +03:00
|
|
|
|
2017-06-26 17:31:34 +03:00
|
|
|
DJANGO_FILTER_INSTALLED = True
|
|
|
|
except ImportError:
|
|
|
|
DJANGO_FILTER_INSTALLED = False
|
2016-09-18 02:29:00 +03:00
|
|
|
|
|
|
|
|
2017-05-25 19:15:13 +03:00
|
|
|
def get_reverse_fields(model, local_field_names):
|
2016-09-18 02:29:00 +03:00
|
|
|
for name, attr in model.__dict__.items():
|
2017-05-25 19:15:13 +03:00
|
|
|
# Don't duplicate any local fields
|
|
|
|
if name in local_field_names:
|
|
|
|
continue
|
|
|
|
|
2019-04-15 15:53:30 +03:00
|
|
|
related = getattr(attr, "rel", None)
|
2017-06-23 14:28:29 +03:00
|
|
|
if isinstance(related, models.ManyToOneRel):
|
2016-12-13 16:23:08 +03:00
|
|
|
yield (name, related)
|
2017-05-25 19:01:29 +03:00
|
|
|
elif isinstance(related, models.ManyToManyRel) and not related.symmetrical:
|
2016-12-13 16:23:08 +03:00
|
|
|
yield (name, related)
|
2016-09-18 02:29:00 +03:00
|
|
|
|
|
|
|
|
|
|
|
def maybe_queryset(value):
|
|
|
|
if isinstance(value, Manager):
|
|
|
|
value = value.get_queryset()
|
|
|
|
return value
|
|
|
|
|
|
|
|
|
|
|
|
def get_model_fields(model):
|
2017-05-25 19:15:13 +03:00
|
|
|
local_fields = [
|
2016-12-13 16:23:08 +03:00
|
|
|
(field.name, field)
|
2018-07-20 02:51:33 +03:00
|
|
|
for field in sorted(
|
|
|
|
list(model._meta.fields) + list(model._meta.local_many_to_many)
|
|
|
|
)
|
2016-12-13 16:23:08 +03:00
|
|
|
]
|
|
|
|
|
2017-05-25 19:01:29 +03:00
|
|
|
# Make sure we don't duplicate local fields with "reverse" version
|
2017-05-25 19:15:13 +03:00
|
|
|
local_field_names = [field[0] for field in local_fields]
|
|
|
|
reverse_fields = get_reverse_fields(model, local_field_names)
|
2017-05-25 19:01:29 +03:00
|
|
|
|
2017-05-25 19:15:13 +03:00
|
|
|
all_fields = local_fields + list(reverse_fields)
|
2016-09-18 02:29:00 +03:00
|
|
|
|
|
|
|
return all_fields
|
|
|
|
|
|
|
|
|
|
|
|
def is_valid_django_model(model):
|
|
|
|
return inspect.isclass(model) and issubclass(model, models.Model)
|
|
|
|
|
|
|
|
|
|
|
|
def import_single_dispatch():
|
|
|
|
try:
|
|
|
|
from functools import singledispatch
|
|
|
|
except ImportError:
|
|
|
|
singledispatch = None
|
|
|
|
|
|
|
|
if not singledispatch:
|
|
|
|
try:
|
|
|
|
from singledispatch import singledispatch
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
|
|
|
|
if not singledispatch:
|
|
|
|
raise Exception(
|
|
|
|
"It seems your python version does not include "
|
|
|
|
"functools.singledispatch. Please install the 'singledispatch' "
|
|
|
|
"package. More information here: "
|
|
|
|
"https://pypi.python.org/pypi/singledispatch"
|
|
|
|
)
|
|
|
|
|
|
|
|
return singledispatch
|