How to join two models in django-rest-framework

Let's say I have two models:

level:

id
file_number
status


level_process:

process_ptr_id
level_id

I want to combine both tables above to display it in one API using django-rest-framework. I am looking for an example on the Internet and I cannot find it ... by the way, I am usingpython 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)
+4
source share
2 answers

Try the following. Create a serializer for your model Level:

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

Then inside LevelProcessSerializerinclude LevelSerializeras follows:

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

    class Meta:
        model = LevelProcess

Use in your ModelViewset:

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

So your json will look something like this:

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

Hope this helps!

+6
source

Do not try to β€œjoin” tables. This is not SQL.

, :

class Level(models.Model):
    .......

class LevelProcess(models.Model):
    level = models.ForeignKey(Level)

,

l = Level.objects.filter(id=level_id).first()
lp = l.level_process_set.all()

Django ORM.

+1

Source: https://habr.com/ru/post/1673943/


All Articles