在Django Rest Framework中结合两个不同的模型

时间:2016-08-25 10:58:43

标签: django django-rest-framework

我有两个无关的模型:

class ModelOne(models.Model):
    fieldA = models.CharField(max_length=50)
    fieldB = models.CharField(max_length=50)

class ModelTwo(models.Model):
    fieldC = models.CharField(max_length=50)
    fieldD = models.CharField(max_length=50)

我想使用DRF构建一个序列化程序,以便我可以像这样返回 json

},...
{ 'fieldA' : 'a',
  'fieldB' : 'b',
  'fieldC' : 'c',
  'fieldD' : 'd'
}, ...

我现在无法做到。我试过了this module,但我遇到了error

2 个答案:

答案 0 :(得分:1)

这样的事情:

from rest_framework.serializers import ModelSerializer

class ModelOneSerializer(ModelSerializer):
    """
    A serializer for ``ModelOne``.
    """
    class Meta(object):
        model = ModelOne


class ModelTwoSerializer(ModelSerializer):
    """
    A serializer for ``ModelTwo``.
    """
    user = ModelOneSerializer()

    class Meta(object):
        model = ModelTwo

答案 1 :(得分:-1)

正如马林所说,你可以这样做:

from rest_framework.serializers import ModelSerializer

class ModelOneSerializer(ModelSerializer):
    """
    A serializer for ``ModelOne``.
    """
    class Meta(object):
        model = ModelOne


class ModelTwoSerializer(ModelSerializer):
    """
    A serializer for ``ModelTwo``.
    """ 
    class Meta(object):
        model = ModelTwo

class ModelThreeSerializer(ModelSerializer):
    """
    A serializer for ``ModelThree``.
    """
    class Meta(object):
        model = ModelThree

class ModelFourSerializer(ModelSerializer):
    """
    A serializer for ``ModelFour``.
    """    
    modelone = ModelOneSerializer()
    modeltwo = ModelTwoSerializer()
    modelthree = ModelThreeSerializer()
    # make it like modelthree = ModelThreeSerializer(source="get_field_from_other_model) if you have foreign key between the models.


    class Meta(object):
        model = ModelFour
        fields = ("modelone", "modeltwo"..)

你也可以

class CombineSerializer(serializers.Serializer):
    modelone = ModelOneSerializer()
    modeltwo = ModelTwoSerializer()
    modelthree = ModelThreeSerializer()
    ....

修改

尝试:覆盖get_queryset方法并使用select_related

class YourList(generics.ListCreateAPIView):

    def get_queryset(self):
        queryset = YourModel.objects.select_related() #use select_related to join table and handle the query.