从2个模型中序列化1 + n个对象,这些对象没有关系

时间:2018-03-12 12:31:47

标签: django python-3.x serialization django-rest-framework

我在2个不同的应用中有2个模块,它们没有任何关系

class Table(models.Model):
    name = models.CharField(max_length=32, unique=True)
    columns = JSONField()

class Company(models.Model):
    name = models.CharField(max_length=32, unique=True)

我需要创建Serializer,首先只序列化1个特定的Table对象(总是相同的)。例如,它麝香是Table.obejects.get(id = 1)。然后我根据View函数中的内容序列化了公司,我发布了以下内容。

这种情况非常重要,因为在中我解释了如何构建表,并在公司中获取数据,我将放入预构建表

公司的Serializer类:

class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ('name',)

查看公司的课程:

class CompanyList(APIView):
    def get_queryset(self):
        return Company.objects.all()

    def get(self, request, format=None):
        companies = self.get_queryset()
        serializer = CompanySerializer(companies, many=True)
        return Response(serializer.data)

2 个答案:

答案 0 :(得分:1)

您可以创建单独的TableSerializer

class TableSerializer(serializers.ModelSerializer):
    class Meta:
        model = Table
        fields = ('name',)

并在CompanySerializer class CompanySerializer(serializers.ModelSerializer): table = SerializerMethodField() class Meta: model = Company fields = ('name',) def get_table(self, obj): table = self.context['table'] return TableSerializer(table).data 内使用它:

table

在视图中,您需要将class CompanyList(APIView): def get_queryset(self): return Company.objects.all() def get(self, request, format=None): companies = self.get_queryset() table = Table.obejects.get(id=1) serializer = CompanySerializer(companies, many=True, context={'table': table}) return Response(serializer.data) 添加到序列化程序SerializerMethodField

{{1}}

答案 1 :(得分:1)

答案是在一个响应中合并2个单独的序列号

为此你需要有2个准备好的序列化器:

class CompanySerializer(serializers.ModelSerializer):
    class Meta:
        model = Company
        fields = ('name',)

class TableSerializer(serializers.ModelSerializer):
    class Meta:
        model = Table
        fields = ('columns',)

然后响应他们作为列表:

class CompanyList(APIView):
    def get_queryset(self):
        return Company.objects.all()

    def get(self, request, format=None):
        companies = self.get_queryset()
        company_serializer = CompanySerializer(companies, many=True)
        table_serializer = TableSerializer(Table.objects.get(name='customers.company'))

        return Response([table_serializer.data, company_serializer.data])