如何从连接表Django模型Serializer中获取多个列

时间:2018-03-27 06:51:56

标签: django django-rest-framework

这是我的型号代码

class questions(models.Model):
q_name = models.CharField(max_length=100)
q_active = models.IntegerField
q_createdby = models.CharField(max_length=100)
q_created = models.DateTimeField(auto_now=True)

def __str__(self):
    return self.q_name

class choice(models.Model):
c_name = models.CharField(max_length=100)
c_question = models.ForeignKey(questions, related_name='choice', on_delete=models.CASCADE)

def __str__(self):
    return self.c_name

我的序列化程序是

class choiceserializer(serializers.ModelSerializer):
c_question = serializers.SlugRelatedField(read_only=True,
                                      slug_field='q_name')

class Meta:
    model = choice
    fields = ('id','c_name','c_question')

这是我的观点

class chl(APIView):

def get(self, request):
    clist = choice.objects.all()
    data = choiceserializer(clist, many = True).data
    return Response(data)

我对序列化程序的输出是

{
    "id": 1,
    "c_name": "name",
    "c_question": "what is your name?"
},

我想用序列化器获取更多列。我想用它来获取q_activeq_created列。我可以使用任何序列化器关系吗?

我需要这个最终的json响应

{
    "id": 
    "c_name": 
    "c_question": 
    "q_active":
    "q_created ":
},

1 个答案:

答案 0 :(得分:0)

class questions(serializers.ModelSerializer):

    class Meta:
        model = questions
        fields = '__all__'

class choiceserializer(serializers.ModelSerializer):
    question = questions()

    class Meta:
        model = Track
        fields = (''id','c_name', 'question')