'How to create ManyToMany object in django view?
I am trying to create product api. Here I have delivery_option
filed which has a manytomamy relation with my product. when I am trying to create product I am getting some error like TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use delivery_option.set() instead
. How to create the many to many field in django?
@api_view(['POST'])
@permission_classes([IsVendor])
def vendorCreateProduct(request):
data = request.data
user = request.user.vendor
print(data['deliveryOption'])
print(data['payment'])
product = Product.objects.create (
user=user,
name=data['name'],
old_price = data['price'],
discount = data['discount'],
image = data['avatar'],
countInStock = data['countInStock'],
subcategory = Subcategory.objects.get_or_create(name=data['subcategory'])[0],
description=data['description'],
delivery_option = data['deliveryOption'],
)
product.available_payment_option.set(data['payment'])
product.save()
serializer = ProductSerializer(product, many=False)
return Response(serializer.data)
Solution 1:[1]
As error says : TypeError: Direct assignment to the forward side of a many-to-many set is prohibited. Use delivery_option.set() instead
It means many-to-many field does not support direct assignment
eg. delivery_option = data['deliveryOption']
.
You've to use add()
or set()
method to add values into your many-to-many field do like this
product = Product.objects.create(...)
product.delivery_option.add(data['deliveryOption'])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ankit Tiwari |