如何覆盖Django中的相关字段?

2024-10-02 02:39:28 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我们有这样的模型

class Product(models.Model):
    name = models.CharField(max_length=100)
    # ...
    main_photo = models.ImageField(upload_to='photos/')

class ProductPhoto(models.Model):
    product = models.ForeignKey(Product, related_name='photos', on_delete=models.CASCADE)
    photo = models.ImageField(upload_to='photos/')

    def __str__(self):
        return self.photo.url

我有两种看法:

  • ProductsView。它提供产品列表,其中包含每种产品的一般信息,仅包括name...main_photo
  • ProductDetailsView。它提供了更详细的信息,包括所有照片
class ProductsView(ListAPIView):
    serializer_class = ProductSerializer


class ProductDetailsView(RetrieveAPIView):
    serializer_class = ProductDetailsSerializer

序列化程序:

class ProductSerializer(ModelSerializer):
    class Meta:
        model = Product
        fields = ('id', 'name', 'main_photo')


class ProductDetailsSerializer(ModelSerializer):
    photos = StringRelatedField(many=True)

    class Meta:
        model = Product
        fields = ('id', 'name', 'main_photo', 'photos')

我希望详细视图提供平面阵列photos中的所有照片,如下[main_photo, ...rest_photos]。 换句话说,, 响应详细视图而不是此视图:

{
    "id": 1,
    "name": "name",
    "main_photo": "/media/photos/main_photo.jpg",
    "photos": [
        "/media/photos/photo1.jpg",
        "/media/photos/photo2.jpg",
        "/media/photos/photo3.jpg"
    ],
}

我想得到这个:

{
    "id": 1,
    "name": "name",
    "photos": [
        "/media/photos/main_photo.jpg",
        "/media/photos/photo1.jpg",
        "/media/photos/photo2.jpg",
        "/media/photos/photo3.jpg"
    ],
}

如何使用django rest框架实现这一点?这个逻辑应该在哪个层次上实现?模型、视图、序列化程序

我想它应该在这里的某个地方,但不太确定它应该是什么样子

class ProductDetailsView(RetrieveAPIView):
    serializer_class = ProductDetailsSerializer

    def get_queryset(self):
        query_set = Product.objects.all()
        # ...
        return query_set

Tags: nameself视图idmainmodelsproductmedia
1条回答
网友
1楼 · 发布于 2024-10-02 02:39:28

对于照片的url,在ProductPhoto中添加一个__str__方法,该方法将只返回照片的url

class ProductPhoto(models.Model):
...

    def __str__(self):
        return self.photo.url

然后像这样改变ProductDetailsSerializer

class ProductDetailsSerializer(ModelSerializer):
    photo_list = serializers.SerializerMethodField()

    def get_photo_list(self, obj):
        db_photos = obj.photos.all()
        result = []
        if obj.main_photo:
            result.append(obj.main_photo.url)
        for p in db_photos:
            result.append(p.photo.url)
        return result   


    class Meta:
        model = Product
        fields = ('id', 'name', 'photo_list')

有关DRFcheck this的更多关系相关文档

相关问题 更多 >

    热门问题