[Python] django-rest-framework, multitable model inheritance, ModelSerializers and nested...

Discussão em 'Python' iniciado por Stack, Março 3, 2025.

  1. Stack

    Stack Membro Participativo

    I can't find this info in the docs or on the interwebs.
    latest django-rest-framework, django 1.6.5

    How does one create a ModelSerializer that can handle a nested serializers where the nested model is implemented using multitable inheritance?

    e.g.

    ######## MODELS
    class OtherModel(models.Model):
    stuff = models.CharField(max_length=255)

    class MyBaseModel(models.Model):
    whaddup = models.CharField(max_length=255)
    other_model = models.ForeignKey(OtherModel)

    class ModelA(MyBaseModel):
    attr_a = models.CharField(max_length=255)

    class ModelB(MyBaseModel):
    attr_b = models.CharField(max_length=255)


    ####### SERIALIZERS
    class MyBaseModelSerializer(serializers.ModelSerializer):
    class Meta:
    model=MyBaseModel

    class OtherModelSerializer(serializer.ModelSerializer):
    mybasemodel_set = MyBaseModelSerializer(many=True)

    class Meta:
    model = OtherModel


    This obviously doesn't work but illustrates what i'm trying to do here.
    In OtherModelSerializer, I'd like mybasemodel_set to serialize specific represenntations of either ModelA or ModelB depending on what we have.

    If it matters, I'm also using django.model_utils and inheritencemanager so i can retrieve a queryset where each instance is already an instance of appropriate subclass.

    Thanks

    Continue reading...

Compartilhe esta Página