如何在django-rest-framework中加入两个模型

时间:2017-04-04 04:01:37

标签: django django-rest-framework

假设我有两种模式:

level:

id
file_number
status


level_process:

process_ptr_id
level_id

我想结合上面的两个表格,使用django-rest-framework在一个API中显示它..我在互联网上寻找这个例子,我找不到它...顺便说一下我的方式使用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)

2 个答案:

答案 0 :(得分:11)

尝试以下方法。为Level模型创建序列化程序:

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

然后,在LevelProcessSerializer内,像这样包含LevelSerializer

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

    class Meta:
        model = LevelProcess

ModelViewset中的用法:

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

这样,你的json看起来像这样:

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

希望这有帮助!

答案 1 :(得分:0)

不要试图“加入”表格。这不是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中的表现。