当我要在url中传递列表对象时,出现此错误
Got AttributeError when attempting to get a value for field `product` on serializer `ProductForParameterSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `int` instance.
Original exception text was: 'int' object has no attribute 'product'.
`
class ProductParameter(models.Model):
product_attribute = models.ForeignKey(ProductAttribute,on_delete=models.CASCADE)
product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name='product_parameters')
parameter = models.CharField(max_length=100,default='-')
和 serializers.py 看起来像这样
class ProductForParameterSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='product.name',max_length=255,read_only=True)
product_desc = serializers.CharField(source='product.description',read_only=True)
image = serializers.ImageField(source='product.image',read_only=True)
price = serializers.DecimalField(source='product.price',max_digits=10,decimal_places=2,read_only=True)
rating = serializers.CharField(source='product.rating',max_length=10,read_only=True)
class Meta:
model = ProductParameter
fields = ('id','product','name','price','product_desc','image','rating')
您可以在模型中看到产品 ForeignKey
。在此模型中,可能有多个产品,并且从此表中我应该获得ID唯一的产品。我不需要重复的产品。为此,我正在使用此视图
class ProductForParameterView(generics.ListAPIView):
serializer_class = ProductForParameterSerializer
def get_queryset(self):
query_params = self.request.query_params
products = query_params.get('product',None)
productParams = []
if products is not None:
for product in products.split('|'):
productParams.append(int(product))
if products is not None:
queryset = ProductParameter.objects.all()
queryset = queryset.filter(product_id__in=productParams)
qs = queryset.values_list('product',flat=True).distinct()
return qs
但是我遇到错误。我怎样才能解决这个问题?预先感谢!