Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize a one to many relation in django-rest using Model serializer?

These are my models and serializers. I want a representation of Question Model along with a list of people the question was asked to.

I am trying this:

@api_view(['GET', 'PATCH'])
def questions_by_id(request,user,pk):
    question = Question.objects.get(pk=pk)
    if request.method == 'GET':
        serializer = QuestionSerializer(question)
        return Response(serializer.data)

But I get an empty dictionary ({}). However when I remove the asked field from QuestionSerializer I get a complete representation of Question along with Places serialized nicely. What am I missing ?

class AskedToSerializer(serializers.ModelSerializer):
    class Meta:
        model = AskedTo
        fields = ('to_user', 'answered')

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        places = PlaceSerializer(many=True, required=False)
        asked = AskedToSerializer(source='askedto_set', many=True)
        fields = ('id', 'created_on', 'title', 'places', 'answered','asked')
        extra_kwargs = {'created_by': {'read_only': True}}

class Question(BaseModel):
    title = models.CharField(max_length=200, null=False)
    places = models.ManyToManyField(Place, blank=True)
    answered = models.BooleanField(default=False)

class AskedTo(BaseModel):
    ques = models.ForeignKey(Question, on_delete=models.CASCADE)
    to_user = models.ForeignKey(settings.AUTH_USER_MODEL)
    replied = models.BooleanField(default=False)


class Place(models.Model):
    g_place_id = models.CharField(max_length=20,primary_key=True)
    json = models.TextField(null=True)
    name = models.CharField(max_length=40)
like image 245
Gaurav Shukla Avatar asked Oct 04 '16 19:10

Gaurav Shukla


1 Answers

I figured it out. There were two errors.

Changed this:

class AskedToSerializer(serializers.ModelSerializer):
    class Meta:
        model = AskedTo
        fields = ('to_user', 'answered')

to this (notice the change in fields, fields on model and serializer didn't match)

class AskedToSerializer(serializers.ModelSerializer):
    class Meta:
        model = AskedTo
        fields = ('to_user', 'replied')

Secondly, I needed to define any extra fields outside class Meta

class QuestionSerializer(serializers.ModelSerializer):
    places = PlaceSerializer(many=True, required=False)
    asked = AskedToSerializer(source='askedto_set', many=True)    

    class Meta:
        model = Question
        fields = ('id', 'created_on', 'title', 'places', 'answered','asked')
        extra_kwargs = {'created_by': {'read_only': True}}

Notice the change in definition of places and asked.

like image 123
Gaurav Shukla Avatar answered Sep 16 '22 18:09

Gaurav Shukla