Django休息帧从PK被引用为FK的所有表中获取值

时间:2015-05-30 20:23:54

标签: python django django-rest-framework

使用我的父模型 - StudioProfile,其他模型与StudioProfile具有外键关系。在向StudioProfile序列化程序发出API请求时,如何获取所有相关表数据。以下是我的模型,视图和序列化器,

class StudioProfile(models.Model):
    name = models.CharField(max_length = 120)
    address_1 = models.CharField(max_length = 200)
    address_2 = models.CharField(max_length = 200)

class StudioServices(models.Model):

    studio_profile = models.ForeignKey(StudioProfile, related_name = "services")
    service_name = models.CharField(max_length = 50)

class StudioPicture(models.Model):

    studio_profile  = models.ForeignKey(StudioProfile, related_name = "pic_of_studio")
    picture = models.ImageField(upload_to = 'img_gallery', null = True, blank = True)

Serializers.py

class StudioServicesSerializer(serializers.ModelSerializer):
    class Meta:
        model = StudioServices
        fields = ('studio_profile',   'service_name')

class StudioPicSerializer(serializers.ModelSerializer):
     class Meta:
         model = StudioPicture
         fields = ('picture') 

class StudioProfileSerializer(serializers.ModelSerializer):
    services = StudioServicesSerializer(source = "StudioServices")
    pic_of_studio = StudioPicSerializer(source = "StudioPicture")
    class Meta:
        model = StudioProfile
        fields = ( 'address_1', 'address_2','services','pic_of_studio' )

views.py

class StudioProfile(ListAPIView):
    permission_classes = (ReadWithoutAuthentication,)
    serializer_class = StudioProfileSerializer
    queryset = StudioProfile.objects.select_related().filter(id = 1)

无法获取数据。我在这做错了什么?当我向StudioProfile课程提出请求时,如何获得所有相关条目。

回溯:

  尝试在序列化程序service_name上获取字段StudioProfileSerializer的值时,

出现AttributeError。   序列化程序字段可能名称不正确,并且与StudioProfile实例上的任何属性或键都不匹配。   原始异常文本是:'StudioProfile'对象没有属性'StudioServices'。

1 个答案:

答案 0 :(得分:1)

我认为您可能需要包含many = true并将源更改为StudioProfileSerializer中的related_name:

class StudioProfileSerializer(serializers.ModelSerializer):
    services = StudioServicesSerializer(many = true, source = "services")
    pic_of_studio = StudioPicSerializer(many = true, source = "pic_of_studio")
    class Meta:
        model = StudioProfile
        fields = ( 'address_1', 'address_2','services','pic_of_studio' )