我的目标是通过name
将Brand
模型的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')
的所有其他属性)。
如果你想作为平面字典返回,你可以这样做。
brand
我解决了自己的问题,通过在brandSerializer
中将ProductSerializer
定义为class ProductSerializer(serializers.HyperlinkedModelSerializer):
brand = BrandSerializer()
class Meta:
model = Product
fields = ('id', 'url', 'sku', 'name', 'brand', 'price')
,我能够将整个品牌对象与产品信息一起返回,就像这样:
qazxswpoi