0

There are hundreds of posts related to an elementary goal.

I have a simple model:

class ModelA(models.Model):
     # I've got only two fields in reality, 
     # but let's suppose there are 150 of them

class ModelB(models.Model):
    # fields

class ModelC(models.Model):
    field_c = Integer
    modelA = models.ForeignKey('ModelB')
    modelB = models.ForeignKey(ModelC)

model_c_instance = ModelC.objects.select_related().get(pk=pk)

All I want to do is to come up with a JSON object which would include the fields for ModelA and ModelB.

  1. Wadofstaff (post) does not suit for Django 1.7 and higher.
  2. This post does not shed light on how I should serialize the objects.
  3. This post tell about Full Serializers, but there's no code snippet to see how it is used.

My final JSON object should look like

[{
    "model": "userinfo", 
    "fields": {
           "field_c ": "9966", 
           "modelA": [{ 
                  # modelA fields
          }
           etc...
    }] 

Do I need REST framework ? Or Full Serializers ?
Please could anyone suggest a structured answer to this topic. I can't come up with a solution for two weeks.

Community
  • 1
  • 1
Edgar Navasardyan
  • 4,261
  • 8
  • 58
  • 121

1 Answers1

0

You want to use a nested relationship. You don't show anything about the userinfo model so this answer doesn't take that into account. You could do something similar to this pseudo-code:

# serializers.py

from rest_framework import serializers


class ModelASerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelA       


class ModelBSerializer(serializers.ModelSerializer):
    class Meta:
        model = ModelB


class ModelCSerializer(serializers.ModelSerializer):
    modelA = ModelASerializer(many=True)
    modelB = ModelBSerializer(many=True)

    class Meta:
        model = ModelC
YPCrumble
  • 26,610
  • 23
  • 107
  • 172