在Django Rest Framework中获取相关模型的值?

Cod*_*mon 6 python django django-rest-framework

我希望以序列化形式获得产品的所有图像.我的模型如下.

class Product():
    title 
    subtitle 
    ...
class ProductImage():
    product = models.ForeignKey(
    'Product', related_name='images', verbose_name=_("Product"))
    image_path
Run Code Online (Sandbox Code Playgroud)

我的序列化器:

class ProductImageSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = ProductImage
        fields = ('caption', 'display_order', 'original', 'product')


class ProductSerializer(serializers.HyperlinkedModelSerializer):

    images = ProductImageSerializer()
    class Meta:
        model = Product
        fields = (
            'title', 'slug', 'short_description', 'description',
            'sku', 'pk', 'images')
Run Code Online (Sandbox Code Playgroud)

我收到了这个错误

尝试在序列化程序`ProductImageSerializer`上获取字段`display_order`的值时,/ api/products/Got AttributeError处的AttributeError.序列化程序字段可能命名不正确,并且不匹配`RelatedManager`实例上的任何属性或键.原始异常文本是:'RelatedManager'对象没有属性'display_order'.

如何获取特定产品的所有图像?

Igo*_*kiy 2

您应该定义相关模型实例的源并设置many=True

images = ProductImageSerializer(many=True, source='images.all')
Run Code Online (Sandbox Code Playgroud)