Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead

  django, python, rest

When i try to post a order i get error saying ‘Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead.’ Any help would be great.

here is my models.py

class OrderItem(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    food_item = models.ForeignKey(FoodItem,on_delete=models.CASCADE)
    quantity = models.IntegerField(default=0,null=True,blank=True)
    size = models.CharField(max_length=10,choices=SIZE_CHOICES,null=True,blank=True)
    date_added = models.DateTimeField(auto_now_add=True)


    def __str__(self):
        return f'{self.quantity} of {self.food_item}'


   
class Order(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
    order = models.ManyToManyField(OrderItem,null=True)
    order_created = models.DateTimeField(auto_now_add=True)
    paid = models.BooleanField(default=False,null=True,blank=True)
    transction_id = models.CharField(max_length=30,unique=True,null=True,blank=True)

    def __str__(self):
        return self.user.username

Here is my serializer.py

class OrderItemListSerializer(serializers.ModelSerializer):
    #user = UserSerializer(many=True,read_only=False)
    class Meta:
        model = OrderItem
        fields = ['id','user','food_item','quantity','size']
    
    def create(self,validated_data):
        return OrderItem.objects.create(**validated_data)

class OrdersSerializer(serializers.ModelSerializer):
    order = OrderItemListSerializer(many=True,)
    class Meta:
        model = Order
        fields = '__all__'
        depth = 0
    
    # def create(self, validated_data):
        
    def create(self,validated_data):
        return Order.objects.create(**validated_data)

here is my views.py

class OrderPost(APIView):
    # add permission to check if user is authenticated
    permission_classes = [permissions.AllowAny]
    
    # 2. Create
    def post(self, request, *args, **kwargs):
        serializer = OrdersSerializer(data=request.data)
        serializer.set(order)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

error


Direct assignment to the forward side of a many-to-many set is prohibited. Use order.set() instead.

Source: Python Questions

LEAVE A COMMENT