在Django中联接2个以上的表

时间:2018-09-13 09:59:43

标签: django django-rest-framework

我正在尝试创建一个新的端点,该端点将返回3个表的联接结果(没有模型类)

我要加入的3个模型是: User Institution Site ,以便显示名称为他们所属的网站。 enter image description here

我已经定义了自己的序列化器,如下所示:

  class DashboardSerializer(serializers.Serializer):
    id = serializers.CharField(read_only=True)
    email = serializers.CharField()
    first_name = serializers.CharField()
    last_name = serializers.CharField()
    full_address = serializers.CharField()
    country = serializers.CharField()
    status = serializers.CharField()
    role = serializers.CharField()
    date_joined = serializers.DateTimeField()
    institution_id = serializers.CharField()
    site_id = serializers.CharField()
    site_name = serializers.CharField()

    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass

和视图集:

class DashboardViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all().select_related('institution_id').select_related('site_id')
    serializer_class = DashboardSerializer

    @api_view(['GET'])
    def get(self, request):
        if request.method == 'GET':
            users = User.objects.all().select_related('institution_id').select_related('site_id')
            serializer = DashboardSerializer(users, many=True)
            return JsonResponse(serializer.data, safe=False)

问题是,当到达终点时,我得到了:

  

select_related中提供的无效字段名称:“ institution_id”,   “ site_id”。选择是:机构

我不确定这是查询,序列化器还是两者都存在的问题。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

添加select_related时,它依赖于字段名,而不是数据库列名。在模型中,您没有institution_id字段,而是institution

来源:https://docs.djangoproject.com/en/2.1/ref/models/querysets/#select-related

据我所知,您不能执行多个级别的select_related,但可以使用prefetch_related

尝试:

User.objects.all().prefetch_related('institution_set, institution_set__site_set')

请在此处查看答案:https://stackoverflow.com/a/27117246/86698