[Fixed]-How to join two models in django-rest-framework

22👍

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!

0👍

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

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

class Meta:
    model = LevelProcess
    fields= "__all__"

-3👍

Don’t try to “join” tables. This isn’t SQL.

I am assuming your model look like Following,

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

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

Now, let’s walk for query,

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

This is how we do in Django ORM.

Leave a comment