0
class V(models.Model):
    title = models.CharField(max_length=100, blank=True, default='')
    doc = models.ForeignKey(D, on_delete=models.CASCADE, default='')
    upload_time = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ('upload_time',)

 class D(models.Model):
    name = models.CharField(max_length=100, blank=True, default='')

    def __str__(self):
        return self.name

in a ModelViewSet I wrote like this:

class index(viewsets.ModelViewSet):
    serializer_class = VSerializer
    queryset = V.objects.all()

I have obtained those data through the API

{
 "id": 1,
 "title": xxxxx
 "d_id": 8,
  ...
  ...
}

However, I wanna the d_id to be more specific, like this:

{
 "id": 1,
 "title": xxxxx
 "d_id": {
     "id": 8,
     "name": xxx,
     ....
   }
...
...
}

So the data in the D Model has been fetched through the d_id=8 and attached into the original queryset.

How could I do this? Need your help...

mrhaoji
  • 336
  • 5
  • 19
  • You should have posted the models. But did you read the extremely comprehensive DRF docs on [serializer relations](http://www.django-rest-framework.org/api-guide/relations/)? What there failed to answer your question? – Daniel Roseman Jun 26 '18 at 07:25
  • @DanielRoseman I have checked the doc that you mentioned. As your point, the "Nested relationships" looks like my answer? – mrhaoji Jun 26 '18 at 07:57

1 Answers1

1

Create a serializer for your model D.

class DSerializer(serializers.ModelSerializer):
    class Meta:
        model = D
        fields = ('field_1', 'field_2', 'field_3')

And in your VSerializer add a serializer field like this:

class VSerializer(serializers.ModelSerializer):
    d = DSerializer() # This will add D's fields in V's API.
    class Meta:
        model = V
        fields = ('field_1', 'field_2', 'field_3')

Read this documentation for more details. http://www.django-rest-framework.org/api-guide/relations/

Hope this helps.

Aakash Rayate
  • 934
  • 7
  • 17
  • I got another similar issue, but unlike this one the D's primary key is not one of the field of V. Could u pls help me figure it out if you got time? thx again! https://stackoverflow.com/questions/51141769/upload-multiple-images-in-django-admin – mrhaoji Jul 03 '18 at 01:47