DetailSerializer具有Listerializer属性

时间:2019-02-21 11:02:56

标签: django django-rest-framework

我想将Listerializer中的json数据添加到DetailSerializer类中。序列化器如下所示: serializer.py

matcher.group(1)

但是一旦查看,我并没有真正看到数据,只看到了细节序列化器数据(驱动程序模型)

class ListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Fastest_laps
        fields = '__all__'

class DetailSerializer(serializers.ModelSerializer):
    listserializer = ListSerializer( read_only=True, many=True)

    class Meta:
        model = Driver
        fields = 
        ('place_of_birth','driver','listserializer','picture')

api.py

class Fastest_laps(models.Model):
    driver_name = models.CharField(max_length=25, null=True)
    grand_prix = models.CharField(max_length=15, blank=True)
    car_model = models.CharField(max_length=50)
    time_taken = models.CharField(blank=True, max_length=8)

    def __str__(self):
        return self.driver_name

class Driver(models.Model):

    place_of_birth = models.CharField(max_length=25)
    driver = models.ForeignKey(Fastest_laps, 
    db_column='driver_name')
    picture = models.ImageField(blank=True, null=True)

    def __str__(self):
        return str(self.driver)

api view

1 个答案:

答案 0 :(得分:0)

您应该将属性重命名为模型名称字段:

class DetailSerializer(serializers.ModelSerializer):
    listserializer = ListSerializer(source='driver', read_only=True)
                                           #^^^^
    class Meta:
        model = Driver
        fields = 
        ('place_of_birth','driver','listserializer','picture')

或添加source属性:

{{1}}