Serializer all models with one serializer

Viewed 522

I'm new in django-rest and during my studies i came across the issue of a unique serialization. Normally, I would create one serializer for each model created, but i want to create just one serializer for all models. In a dynamic way.

[EDIT]

I'm using Django REST Framework integration with SQLAlchemy, so models came from sqlalchemy. I'm using django-rest-witchcraft too, who offering supported for sqlalchemy orm.

Example:

models.py

class Group(Base):
    __tablename__ = 'groups'

    id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
    name = sa.Column(sa.String())


class User(Base):
    __tablename__ = 'users'

    id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
    name = sa.Column(sa.String())
    fullname = sa.Column(sa.String())
    password = sa.Column(sa.String())

    _group_id = sa.Column('group_id', sa.Integer(), sa.ForeignKey('groups.id'))
    group = sa.orm.relationship(Group, backref='users')


class Address(Base):
    __tablename__ = 'addresses'

    id = sa.Column(sa.Integer(), primary_key=True, autoincrement=True)
    email_address = sa.Column(sa.String(), nullable=False)

    _user_id = sa.Column(sa.Integer(), sa.ForeignKey('users.id'))
    user = sa.orm.relationship(User, backref='addresses')

I try to do something like this:

class GeneralSerializer(serializers.ModelSerializer):
    class Meta:
        model = None
        session = session
        fields = '__all__'

But I'm getting a NoneType as an answer:

sqlalchemy.exc.NoInspectionAvailable: No inspection system is available for object of type <class 'NoneType'>

Which makes sense, considering the skeleton of the serializer. I know this question was asked before, but I found no solution in the previous topic and nowhere else. I will probably have to work with the serializer init, but I still have no idea how to do it.

I don't want a ready answer, of course, just an idea of ​​how to do this.

1 Answers

Django's ModelSerializer works for Django models but you're using SQLAlchemy which isn't part of Django. So this isn't going to work.

Django also doesn't provide a way to serialize multiple models as part of the same serializer.

What you can do is to Create a field for users in your Group serializer - that way you can have all users with their nested address in one place:

class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
    users = serializers.RelatedField(source='user', read_only=True)
Related