Django(REST框架)-如何向queryset迭代添加字段



我需要一些关于在Django(DRF(中进行查询的建议。

我试图为Products创建一个查询集,其中每个Product都有一个字段";图像";该产品的所有图像(文件((使用ProductImage模型耦合(,但我不知道如何添加字段。

下面是我的ProductViewSet

class ProductViewSet(viewsets.ModelViewSet):
serializer_class = ProductSerializer
queryset = Product.objects.all()
def get_queryset(self): 
queryset = Product.objects.all()
product_list = []
# iterate over all products
for product in queryset:
# find Image ids for product
image_ids = list(ProductImage.objects.filter(product=product.id).values_list('image', flat=True))
images = []
# iterate over images and add to images list
for image_id in image_ids:
image = list(File.objects.filter(id=image_id).all())
images.append(image)
# add images field to product
# product['images'] = images # "TypeError: 'Product' object does not support item assignment"
product.images = images # Doesn't do anything.
# add product to product list
product_list.append(product)
return product_list

我试着做以下操作来添加字段";图像":

product['images'] = images

这给出了误差"0";TypeError:"Product"对象不支持项分配">

product.images = images 

它什么都不做。。。

有人能给我指正确的方向吗?任何关于如何以更好的方式进行查询的提示也欢迎!

您的"产品"模型是否具有具有正确数据类型的现有"图像"字段?

否则,您将无法使用文件对象列表更新它。

更好的解决方案可能是"ProductImage"one_answers"Product"之间的多对一模型关系。

然后,Django将能够更好地通过ORM自动返回您的图像,而不是复杂的定制查询。https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/

如果不查看其他模型,很难给出确切的答案,但如果您编写一个更健壮的查询并使用annotate,则可以在过滤器集和序列化程序上访问带注释的字段。

尝试使用dict,product_list={}product_list[product]=images

删除

product.images = images # Doesn't do anything.
# add product to product list
product_list.append(product)

最新更新