在django REST框架上的筛选get请求中包含来自另一个引用模型的属性

问题描述 投票:0回答:2

我的目标是通过nameBrand模型的Product属性包含在models.ForeignKey中,当我提出产品请求时。这段代码到底在python shell中返回的是什么:

Product.objects.all().values('name', 'brand__name',)

返回:

[
    {'name': 'B-1', 'brand__name': 'B-brand'}, 
    {'name': 'B-2', 'brand__name': 'B-brand'}, 
    {'name': 'C-1', 'brand__name': 'C-brand'}
]

我已经使用django-filters来过滤我的获取请求。

楷模:

class Brand(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name


class Product(models.Model):
    name = models.CharField(max_length=255)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE, default=None)

    def __str__(self):
        return self.name

串行器:

class BrandSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Brand
        fields = ('id', 'url', 'name')


class ProductSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Product
        fields = ('id', 'url', 'name', 'brand')

过滤:

class ProductFilter(filters.FilterSet):
    name = filters.CharFilter(lookup_expr = 'icontains')
    brand__name = filters.CharFilter(lookup_expr = 'icontains')

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

视图:

class ProductView(viewsets.ModelViewSet):
    queryset = Product.objects.all()
    serializer_class = ProductSerializer
    filterset_class = ProductFilter

在filterSet中使用brand__name,我能够引用某个产品引用并检索它的品牌模型的名称。当我制作get request时,我的目标是还包括品牌的相同名称以及产品的属性,Product目前仅产生品牌的url /参考(以及class ProductSerializer(serializers.HyperlinkedModelSerializer): brand_name = serializer.CharField(source="brand__name") class Meta: model = Product fields = ('id', 'url', 'sku', 'name', 'brand_name', 'price') 的所有其他属性)。

django django-models django-rest-framework django-views django-filter
2个回答
0
投票

如果你想作为平面字典返回,你可以这样做。

brand

0
投票

我解决了自己的问题,通过在brandSerializer中将ProductSerializer定义为class ProductSerializer(serializers.HyperlinkedModelSerializer): brand = BrandSerializer() class Meta: model = Product fields = ('id', 'url', 'sku', 'name', 'brand', 'price') ,我能够将整个品牌对象与产品信息一起返回,就像这样:

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.