mrhaoji
mrhaoji

Reputation: 336

Get a queryset from another Model in a queryset in Django

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...

Upvotes: 0

Views: 1115

Answers (1)

Aakash Rayate
Aakash Rayate

Reputation: 934

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.

Upvotes: 1

Related Questions