过滤嵌套的序列化程序和Foreing Key Django / Rest Framework

时间:2018-08-05 03:35:31

标签: django django-rest-framework

以下是我的模型课程

class ProductClass(models.Model):
    name = models.CharField('Name')

class Product(models.Model):
    title = models.CharField('Product title')
    description = models.TextField('Description')
    product_class = models.ForeignKey(ProductClass, null=True, blank=True, related_name='products')

class ProductPriceRepository(models.Model):
    product = models.ForeignKey(Product, related_name='price_repo')

    price = models.DecimalField('price of product', max_digits=7, decimal_places=2)

    location = models.ForeignKey(Location,blank=True, null=True, related_name='price_repo')

    is_default = models.BooleanField()

这就是我定义视图的方式

class ProductClassList(APIView):
    def get(self, request, format=None):
        product_classes = ProductClass.objects.filter(products__price_repo__is_default=True)
        serializer = ProductClassSerializer(product_classes, many=True)
        return Response(serializer.data)

我已定义序列化如下

class ProductPriceRepositorySerializer(serializers.ModelSerializer):
    class Meta:
        model = ProductPriceRepository
        fields = ('price',)


class ProductSerializer(serializers.ModelSerializer):
    price = SerializerMethodField()

    class Meta:
        model = Product
        fields = ('title', 'description', 'price')

    def get_price(self, obj):
        for price in obj.price_repo.all():
            if price.is_default:
                serializer = ProductPriceRepositorySerializer(price)
                return serializer.data


class ProductClassSerializer(serializers.ModelSerializer):
    products = SerializerMethodField()

    class Meta:
        model = ProductClass
        fields = ('name', 'products')

    def get_products(self, obj):
        for product in obj.products.all():
            for price in product.price_repo.all():
                if price.is_default:
                    serializer = ProductSerializer(product)
                    return serializer.data

输出类似于

[     {         “名称”:“产品类别测试一”,         “产品”:{             “ title”:“测试产品一”,             “ description”:“”,             “价钱”: {                 “ price”:“ 100.00”             }         }     },     {         “名称”:“产品类别测试二”,         “产品”:{             “ title”:“测试产品二”,             “ description”:“”,             “价钱”: {                 “ price”:“ 30.00”             }         }     } ]

我正在使用SerializerMethodField来过滤给定产品类别的默认价格是否有更多的传出方法来实现相同的目的?

1 个答案:

答案 0 :(得分:1)

尝试这样的事情,

class ProductClassSerializer(serializers.ModelSerializer):
    products = serializers.SerializerMethodField()

    class Meta:
        model = ProductClass
        fields = ('name', 'products')

    def get_products(self, obj):
        return ProductSerializer(ProductPriceRepository.objects.filter(is_default=True, product__product_class=obj),
                                 many=True).data