Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two models in django-rest-framework

Let say i have two models:

level:

id
file_number
status


level_process:

process_ptr_id
level_id

I want to combine both of my table above to display it in one API using django-rest-framework.. I'm looking for the example on the internet and i cannot find it...by the way i'm using python 2.7 , django 1.10.5 and djangorestframework 3.6.2

serializer.py

class LevelSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()
    class Meta:
        model = Level
        fields = ('__all__')

class LevelProcessSerializer(serializers.ModelSerializer):
    level = LevelSerializer(read_only=True)

    class Meta:
        model = LevelProcess
        fields = ('__all__')

views.py

class ViewLevelProcessViewSet(viewsets.ModelViewSet):
    processes = LevelProcess.objects.all()
    serializer_class = LevelProcessSerializer(processes, many=True)
like image 563
MunirohMansoor Avatar asked Apr 04 '17 04:04

MunirohMansoor


People also ask

What is Queryset in Django REST framework?

The root QuerySet provided by the Manager describes all objects in the database table. Usually, though, you'll need to select only a subset of the complete set of objects. The default behavior of REST framework's generic list views is to return the entire queryset for a model manager.

What is To_representation in Django?

to_representation(self, value) method. This method takes the target of the field as the value argument, and should return the representation that should be used to serialize the target. The value argument will typically be a model instance.

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.


1 Answers

Try the following. Create serializer for your Level model:

class LevelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Level

Then, inside LevelProcessSerializer, include LevelSerializer like this:

class LevelProcessSerializer(serializers.ModelSerializer):
    level = LevelSerializer(read_only=True)

    class Meta:
        model = LevelProcess

Usage in your ModelViewset:

class ViewLevelProcessViewSet(viewsets.ModelViewSet):
    queryset = LevelProcess.objects.all() 
    serializer_class = LevelProcessSerializer

This way, your json will look something like this:

{
   "id": 1,
   "level": {
      "id": 3,
      "status": "red"
   }
}

Hope this helps!

like image 188
Jahongir Rahmonov Avatar answered Nov 15 '22 15:11

Jahongir Rahmonov