【问题标题】:Could not display Product image in an API无法在 API 中显示产品图片
【发布时间】:2016-07-24 06:16:35
【问题描述】:

我一直在尝试使用 Django Rest Framework 设计一个用于创建移动应用程序的 REST API。我可以为商店列表设计一个 API,显示商店所有者(商家)信息、商店信息、商店类别和产品,但不显示产品图片。为什么我的代码没有显示产品图片?谁能给我一个想法或建议,为什么它不起作用?

我的代码

我的models.py

class Store(models.Model):
    merchant = models.ForeignKey(Merchant)
    name_of_store = models.CharField(max_length=100)
    store_off_day = MultiSelectField(choices=DAY, max_length=7, default='Sat')
    store_categories = models.ManyToManyField('StoreCategory',blank=True)

    class Meta:
        verbose_name = 'Store'


class Product(models.Model):
    store = models.ForeignKey(Store)
    name_of_product = models.CharField(max_length=120)
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(decimal_places=2, max_digits=20)
    # categories = models.ManyToManyField('Category',blank=True)


class ProductImage(models.Model):
    product = models.ForeignKey(Product)
    image = models.ImageField(upload_to='products/images/')
    updated = models.DateTimeField(auto_now_add=False, auto_now=True)

class StoreCategory(models.Model):
    product = models.ForeignKey(Product,null=True, on_delete=models.CASCADE,related_name="store_category")
    store_category = models.CharField(choices=STORE_CATEGORIES, default='GROCERY', max_length=10)

Serializers.py

class ProductImageSerializer(ModelSerializer):
    class Meta:
        model = ProductImage
        fields  =   ('id','image', )

class ProductSerializers(ModelSerializer):
    image = ProductImageSerializer(many=True,read_only=True)
    class Meta:
        model = Product
        fields=('id','image','name_of_product','description','price','active',)

class StoreCategorySerializer(ModelSerializer):
    product = ProductSerializers(read_only=True)
    class Meta:
        model = StoreCategory

class StoreSerializer(ModelSerializer):
    # url = HyperlinkedIdentityField(view_name='stores_detail_api')
    store_categories = StoreCategorySerializer(many=True) 
    merchant = MerchantSerializer(read_only=True)
    class Meta:
        model = Store
        fields=("id",
                # "url",
                "merchant",
                "store_categories",
                "name_of_store",
                "store_contact_number",
                "store_off_day",
                )

我的 API

【问题讨论】:

    标签: python django api django-rest-framework


    【解决方案1】:

    在你的 models.py 中创建:

    import os
    

    从您的 ProductImage 模型中删除产品外键:

    class ProductImage(models.Model):
        image = models.ImageField(upload_to='products/images/')
        updated = models.DateTimeField(auto_now_add=False, auto_now=True)
    
        @property
        def imagename(self):
            return str(os.path.basename(self.image.name))
    

    将图像外键添加到您的产品中

    class Product(models.Model):
        image = models.ForeignKey(ProductImage,blank=True,null=True)
        store = models.ForeignKey(Store)
        name_of_product = models.CharField(max_length=120)
        description = models.TextField(blank=True, null=True)
        price = models.DecimalField(decimal_places=2, max_digits=20)
        # categories = models.ManyToManyField('Category',blank=True)
    

    然后在您的 serializers.py 中

    class ProductImageSerializer(ModelSerializer):
        class Meta:
            model = ProductImage
            fields  =   ('id','imagename', )
    
    class ProductSerializers(ModelSerializer):
        image = ProductImageSerializer(many=False,read_only=True) #only one image used
        class Meta:
            model = Product
            fields=('id','image','name_of_product','description','price','active',)
    

    这样你就可以得到实际的图像名称和位置。

    【讨论】:

    • 完全按照你说的做,但是 API 中没有显示静止图像字段。
    • 您的外键引用有误,而不是从 Product 引用它,而是从 ProductImage 引用它。查看更新的代码。
    • 是的,它现在正在工作。谢谢你的帮助。最后一个问题,看看我的数据库模型或者说 enitites,你觉得我的模型和 API 设计怎么样?我做对了吗?我只需要你的反馈(我是初学者),如果你有时间而不是代码。
    • 不客气。是的,我觉得不错。你练习得越多越好。您还可以为每个序列化程序创建单独的视图集以帮助您查看结果。
    • 我理解你。你真的一针见血。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多