From e6f575400bced2992e60e245dbcb914f8dc14a0c Mon Sep 17 00:00:00 2001 From: Denis K Date: Tue, 25 Dec 2018 21:43:09 +0300 Subject: [PATCH] Add relations --- jet_bridge/serializers/model_description.py | 21 ++++++++++++++++++++- jet_bridge/views/model_description.py | 21 ++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/jet_bridge/serializers/model_description.py b/jet_bridge/serializers/model_description.py index a26021d9..1be4a4c5 100644 --- a/jet_bridge/serializers/model_description.py +++ b/jet_bridge/serializers/model_description.py @@ -4,8 +4,8 @@ class ModelDescriptionFieldSerializer(Serializer): name = fields.CharField() - field = fields.CharField() db_column = fields.CharField() + field = fields.CharField() filterable = fields.BooleanField() editable = fields.BooleanField() params = fields.JSONField() @@ -21,11 +21,29 @@ class Meta: ) +class ModelDescriptionRelationSerializer(Serializer): + name = fields.CharField() + related_model = fields.JSONField() + field = fields.CharField() + related_model_field = fields.CharField() + through = fields.JSONField() + + class Meta: + fields = ( + 'name', + 'related_model', + 'field', + 'related_model_field', + 'through', + ) + + class ModelDescriptionSerializer(Serializer): model = fields.CharField() db_table = fields.CharField() hidden = fields.BooleanField() fields = ModelDescriptionFieldSerializer(many=True) + relations = ModelDescriptionRelationSerializer(many=True) class Meta: fields = ( @@ -33,4 +51,5 @@ class Meta: 'db_table', 'hidden', 'fields', + 'relations', ) diff --git a/jet_bridge/views/model_description.py b/jet_bridge/views/model_description.py index 10f0859a..c8480952 100644 --- a/jet_bridge/views/model_description.py +++ b/jet_bridge/views/model_description.py @@ -1,4 +1,5 @@ from sqlalchemy import inspect +from sqlalchemy.orm.base import ONETOMANY from jet_bridge.db import Session, MappedBase from jet_bridge.models import data_types @@ -36,6 +37,23 @@ def map_column(column): 'params': params } + def map_relation(relation): + field = None + through = None + + if relation.direction == ONETOMANY: + field = 'ManyToOneRel' + + return { + 'name': relation.key, + 'related_model': { + 'model': relation.table.name + }, + 'field': field, + 'related_model_field': relation.primaryjoin.right.name, + 'through': through + } + def map_table(cls): mapper = inspect(cls) name = mapper.selectable.name @@ -43,7 +61,8 @@ def map_table(cls): 'model': name, 'db_table': name, 'fields': list(map(map_column, mapper.columns)), - 'hidden': name in hidden + 'hidden': name in hidden, + 'relations': list(map(map_relation, filter(lambda x: x.direction == ONETOMANY, mapper.relationships))) } return list(map(map_table, MappedBase.classes))