'Django:all instances have the same many-to-many field

I have custom user model, and this user has many-to-many field called classes. When the user creates new class I add it to the many-to-many field classes . But the problem is ,not only this user points to added classes but all users created, point to the same classes. How can I organize models such that a when I add class_instance to many-to-many field classes of single user, only this user has those classes. Here is my code

models.py

class Class (models.Model):
   key=models.CharField(max_length=256,unique=True);
   name=models.CharField(max_length=256);
   def __str__(self):
       return self.name;

class NewUser(AbstractBaseUser,PermissionsMixin):
       email=models.EmailField(max_length=255,unique=True,default=NULL,)
       name=models.CharField(max_length=255)
       surname=models.CharField(max_length=255)
       is_staff=models.BooleanField(default=False)
       is_active=models.BooleanField(default=True) 
       is_teacher=models.BooleanField(default=False)
       classes=models.ManyToManyField(Class)
       objects=CustomUserManager();
       USERNAME_FIELD='email'
       REQUIRED_FIELDS=['name','surname','is_teacher']

       def __str__(self) :
           return self.name



views.py

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def create_class(request):
    instance=NewUser.objects.all().filter(id=request.user.id) #getting the user from request(I want only this user to have the added class_instance)
    serializer=ClassSerializer(data=request.data);
    if serializer.is_valid():
     class_instance=serializer.save();
     class_instance.save();
     instance[0].classes.add(class_instance); #adding the  created class to  many-to-many class field
     instance[0].save();
     data={
         'id':instance.id
     }
    return  JsonResponse(data)


Solution 1:[1]

I think instance object doesn't need to be created. And instance[0].save() isn't also necessary because add function actually saves data.

from rest_framework.response import Response
from rest_framework import status

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def create_class(request):
    serializer = ClassSerializer(data=request.data);
    if serializer.is_valid():
        class_instance = serializer.save();
        request.user.classes.add(class_instance)            
        data={
            'id':request.user.id
        }
        return  JsonResponse(data)
    else:
        return Response(status=status.HTTP_400_BAD_REQUEST)

Hope it could help.

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 David Lu