我想实现这一目标:获取类别所有产品的API。
class Category(models.Model):
main_category = models.CharField(max_length=200, default = '')
def __str__(self):
return '%s' % (self.main_category)
class Subcategory(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
sub_category = models.CharField(max_length=200, default = '')
def __str__(self):
return '%s' % (self.sub_category)
class Products(models.Model):
sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE)
product_name = models.CharField(max_length=200, default = '')
def __str__(self):
return '%s' % (self.product_name)
class ProductCategoryFilter(django_filters.FilterSet):
category = django_filters.CharFilter(name="category__main_category")
class Meta:
model = Products
fields = ['category']
class ProductCategoryListAPIView(ListAPIView):
queryset = Products.objects.all()
serializer_class = ProductCategorySerializer
filter_class = ProductCategoryFilter
class ProductCategorySerializer(ModelSerializer):
#category_name = serializers.CharField(source='category.main_category')
category_name = CategorySerializer(source='category_set')
class Meta:
model = Products
fields = [
'category_name',
'product_name',
]
尝试在序列化程序AttributeError
上获取字段category_name
的值时,我得到ProductCategorySerializer
。序列化程序字段可能名称不正确,并且与Products
实例上的任何属性或键都不匹配。
原始例外文字是:'产品'对象没有属性'类别'。
我希望输出如下:
[
{
"category_name": "main category 1",
"product_name": "product 1"
},
{
"category_name": "main category 1",
"product_name": "product 2"
},..........
OR输出如下:
[
{
"main category 1" :{ "product 1", "product 2"...}