I have a Tender model and a Product model. There is a foreign key relationship between Tender and product.
Now I want to update a tender instance where I provide tender and product data. The data format is multipart/form-data. But every time get the following error
{
“products”: [
“This field is required.”
]
}
I am providing the code so that you guys can understand things properly
This is the view class
@extend_schema(tags=[OpenApiTags.TMS_TENDER])
class TenderUpdateView(generics.UpdateAPIView):
permission_classes = []
queryset = Tender.objects.all()
serializer_class = TenderPreSubmissionSerializer
lookup_field = "id"
parser_classes = [MultiPartParser]
def get_queryset(self):
id = self.kwargs.get("id")
return Tender.objects.filter(id=id)
This is the serializer
class TenderPreSubmissionSerializer(serializers.ModelSerializer):
products = ProductSerializer(many=True)
class Meta:
model = Tender
fields = [
"products",
"is_open",
"procuring_entity",
"ministry",
"bg_amount",
"bg_attachment",
"bg_issue_date",
"bg_validity_date",
"is_bg_extended",
]
def update(self, instance, validated_data):
# Extract products data
products_data = validated_data.pop("products")
# Update tender instance
instance = super().update(instance, validated_data)
# Create a mapping of existing products by ID
existing_products = {product.id: product for product in instance.products.all()}
# Update or create products
for product_data in products_data:
product_id = product_data.get("id")
if product_id and product_id in existing_products:
# Update existing product
product = existing_products.pop(product_id)
for attr, value in product_data.items():
setattr(product, attr, value)
product.save()
else:
# Create new product
Product.objects.create(**product_data)
# Delete products that are not in the new list
for product in existing_products.values():
product.delete()
return instance