Polymorphically serializing objects in django











up vote
0
down vote

favorite












I have the following object inheritance model.



class Room:
name = models.CharField(db_index=True, unique=True, max_length=255)
status = models.CharField(default=RoomStatus.ACTIVE, max_length=256, null=True)
members = models.ManyToManyField(User)
last_activity = models.DateTimeField(default=timezone.now)


And the inherited models are,



class LeagueRoom(Room):
league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
logo_url = models.CharField(max_length=1024, null=True)


and



class ClubRoom(Room):
club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
logo_url = models.CharField(max_length=1024, null=True)


The respective Serializers are as follows,



class RoomSerializer(serializers.ModelSerializer):
members = UserSerializer(read_only=True, many=True)

class Meta:
model = Room
fields = ('id', 'name', 'status', 'members', 'created', 'modified', 'last_active')


and



class LeagueRoomSerializer(serializers.ModelSerializer):
location = LocationSerializer(read_only=True)
league = LeagueSerializer(read_only=True)
room = RoomSerializer(read_only=True)

class Meta:
model = LeagueRoom
fields = ('id', 'name', 'location', 'status', 'league',
'logo_url', 'room', 'created', 'modified',)


and



class ClubRoomSerializer(serializers.ModelSerializer):
location = LocationSerializer(read_only=True)
club = ClubSerializer(read_only=True)
room = RoomSerializer(read_only=True)

class Meta:
model = ClubRoom
fields = ('id', 'name', 'location', 'club', 'logo_url',
'status', 'room', 'created', 'modified',)


My problem is that I have fetched all rooms for an user in the following manner.



rooms = user.room_set.order_by('-last_activity')


Now I want to Serialize this data based on the room type. Thus instead of using the RoomSerializer I want to traverse the list of rooms and if the room is ClubRoom, then use ClubRoomSerializer or else LeagueRoomSerializer.
I'm not sure how to determine the child object from the parent.



Can someone help me with this.










share|improve this question


























    up vote
    0
    down vote

    favorite












    I have the following object inheritance model.



    class Room:
    name = models.CharField(db_index=True, unique=True, max_length=255)
    status = models.CharField(default=RoomStatus.ACTIVE, max_length=256, null=True)
    members = models.ManyToManyField(User)
    last_activity = models.DateTimeField(default=timezone.now)


    And the inherited models are,



    class LeagueRoom(Room):
    league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
    logo_url = models.CharField(max_length=1024, null=True)


    and



    class ClubRoom(Room):
    club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
    logo_url = models.CharField(max_length=1024, null=True)


    The respective Serializers are as follows,



    class RoomSerializer(serializers.ModelSerializer):
    members = UserSerializer(read_only=True, many=True)

    class Meta:
    model = Room
    fields = ('id', 'name', 'status', 'members', 'created', 'modified', 'last_active')


    and



    class LeagueRoomSerializer(serializers.ModelSerializer):
    location = LocationSerializer(read_only=True)
    league = LeagueSerializer(read_only=True)
    room = RoomSerializer(read_only=True)

    class Meta:
    model = LeagueRoom
    fields = ('id', 'name', 'location', 'status', 'league',
    'logo_url', 'room', 'created', 'modified',)


    and



    class ClubRoomSerializer(serializers.ModelSerializer):
    location = LocationSerializer(read_only=True)
    club = ClubSerializer(read_only=True)
    room = RoomSerializer(read_only=True)

    class Meta:
    model = ClubRoom
    fields = ('id', 'name', 'location', 'club', 'logo_url',
    'status', 'room', 'created', 'modified',)


    My problem is that I have fetched all rooms for an user in the following manner.



    rooms = user.room_set.order_by('-last_activity')


    Now I want to Serialize this data based on the room type. Thus instead of using the RoomSerializer I want to traverse the list of rooms and if the room is ClubRoom, then use ClubRoomSerializer or else LeagueRoomSerializer.
    I'm not sure how to determine the child object from the parent.



    Can someone help me with this.










    share|improve this question
























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I have the following object inheritance model.



      class Room:
      name = models.CharField(db_index=True, unique=True, max_length=255)
      status = models.CharField(default=RoomStatus.ACTIVE, max_length=256, null=True)
      members = models.ManyToManyField(User)
      last_activity = models.DateTimeField(default=timezone.now)


      And the inherited models are,



      class LeagueRoom(Room):
      league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
      location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
      logo_url = models.CharField(max_length=1024, null=True)


      and



      class ClubRoom(Room):
      club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True)
      location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
      logo_url = models.CharField(max_length=1024, null=True)


      The respective Serializers are as follows,



      class RoomSerializer(serializers.ModelSerializer):
      members = UserSerializer(read_only=True, many=True)

      class Meta:
      model = Room
      fields = ('id', 'name', 'status', 'members', 'created', 'modified', 'last_active')


      and



      class LeagueRoomSerializer(serializers.ModelSerializer):
      location = LocationSerializer(read_only=True)
      league = LeagueSerializer(read_only=True)
      room = RoomSerializer(read_only=True)

      class Meta:
      model = LeagueRoom
      fields = ('id', 'name', 'location', 'status', 'league',
      'logo_url', 'room', 'created', 'modified',)


      and



      class ClubRoomSerializer(serializers.ModelSerializer):
      location = LocationSerializer(read_only=True)
      club = ClubSerializer(read_only=True)
      room = RoomSerializer(read_only=True)

      class Meta:
      model = ClubRoom
      fields = ('id', 'name', 'location', 'club', 'logo_url',
      'status', 'room', 'created', 'modified',)


      My problem is that I have fetched all rooms for an user in the following manner.



      rooms = user.room_set.order_by('-last_activity')


      Now I want to Serialize this data based on the room type. Thus instead of using the RoomSerializer I want to traverse the list of rooms and if the room is ClubRoom, then use ClubRoomSerializer or else LeagueRoomSerializer.
      I'm not sure how to determine the child object from the parent.



      Can someone help me with this.










      share|improve this question













      I have the following object inheritance model.



      class Room:
      name = models.CharField(db_index=True, unique=True, max_length=255)
      status = models.CharField(default=RoomStatus.ACTIVE, max_length=256, null=True)
      members = models.ManyToManyField(User)
      last_activity = models.DateTimeField(default=timezone.now)


      And the inherited models are,



      class LeagueRoom(Room):
      league = models.ForeignKey(League, on_delete=models.CASCADE, null=True)
      location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
      logo_url = models.CharField(max_length=1024, null=True)


      and



      class ClubRoom(Room):
      club = models.ForeignKey(Club, on_delete=models.CASCADE, null=True)
      location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True)
      logo_url = models.CharField(max_length=1024, null=True)


      The respective Serializers are as follows,



      class RoomSerializer(serializers.ModelSerializer):
      members = UserSerializer(read_only=True, many=True)

      class Meta:
      model = Room
      fields = ('id', 'name', 'status', 'members', 'created', 'modified', 'last_active')


      and



      class LeagueRoomSerializer(serializers.ModelSerializer):
      location = LocationSerializer(read_only=True)
      league = LeagueSerializer(read_only=True)
      room = RoomSerializer(read_only=True)

      class Meta:
      model = LeagueRoom
      fields = ('id', 'name', 'location', 'status', 'league',
      'logo_url', 'room', 'created', 'modified',)


      and



      class ClubRoomSerializer(serializers.ModelSerializer):
      location = LocationSerializer(read_only=True)
      club = ClubSerializer(read_only=True)
      room = RoomSerializer(read_only=True)

      class Meta:
      model = ClubRoom
      fields = ('id', 'name', 'location', 'club', 'logo_url',
      'status', 'room', 'created', 'modified',)


      My problem is that I have fetched all rooms for an user in the following manner.



      rooms = user.room_set.order_by('-last_activity')


      Now I want to Serialize this data based on the room type. Thus instead of using the RoomSerializer I want to traverse the list of rooms and if the room is ClubRoom, then use ClubRoomSerializer or else LeagueRoomSerializer.
      I'm not sure how to determine the child object from the parent.



      Can someone help me with this.







      python django django-orm






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 8 at 23:51









      Melissa Stewart

      754622




      754622
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          class RoomSerializer(serializers.Serializer):
          def to_representation(self, instance):
          if isinstance(instance, LeagueRoom)
          serializer_class = LeagueRoomSerializer
          elif isinstance(instance, ClubRoom):
          serializer_class = ClubRoomSerializer
          return serializer_class(instance=instance).data

          queryset = user.room_set.order_by('-last_activity')
          serialized = RoomSerializer(queryset, many=True).data





          share|improve this answer





















            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














             

            draft saved


            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53217869%2fpolymorphically-serializing-objects-in-django%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            1
            down vote



            accepted










            class RoomSerializer(serializers.Serializer):
            def to_representation(self, instance):
            if isinstance(instance, LeagueRoom)
            serializer_class = LeagueRoomSerializer
            elif isinstance(instance, ClubRoom):
            serializer_class = ClubRoomSerializer
            return serializer_class(instance=instance).data

            queryset = user.room_set.order_by('-last_activity')
            serialized = RoomSerializer(queryset, many=True).data





            share|improve this answer

























              up vote
              1
              down vote



              accepted










              class RoomSerializer(serializers.Serializer):
              def to_representation(self, instance):
              if isinstance(instance, LeagueRoom)
              serializer_class = LeagueRoomSerializer
              elif isinstance(instance, ClubRoom):
              serializer_class = ClubRoomSerializer
              return serializer_class(instance=instance).data

              queryset = user.room_set.order_by('-last_activity')
              serialized = RoomSerializer(queryset, many=True).data





              share|improve this answer























                up vote
                1
                down vote



                accepted







                up vote
                1
                down vote



                accepted






                class RoomSerializer(serializers.Serializer):
                def to_representation(self, instance):
                if isinstance(instance, LeagueRoom)
                serializer_class = LeagueRoomSerializer
                elif isinstance(instance, ClubRoom):
                serializer_class = ClubRoomSerializer
                return serializer_class(instance=instance).data

                queryset = user.room_set.order_by('-last_activity')
                serialized = RoomSerializer(queryset, many=True).data





                share|improve this answer












                class RoomSerializer(serializers.Serializer):
                def to_representation(self, instance):
                if isinstance(instance, LeagueRoom)
                serializer_class = LeagueRoomSerializer
                elif isinstance(instance, ClubRoom):
                serializer_class = ClubRoomSerializer
                return serializer_class(instance=instance).data

                queryset = user.room_set.order_by('-last_activity')
                serialized = RoomSerializer(queryset, many=True).data






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 9 at 0:09









                rikAtee

                4,61042855




                4,61042855






























                     

                    draft saved


                    draft discarded



















































                     


                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53217869%2fpolymorphically-serializing-objects-in-django%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Schultheiß

                    Verwaltungsgliederung Dänemarks

                    Liste der Kulturdenkmale in Wilsdruff