Search code examples
djangopython-3.xdjango-modelsdjango-managers

Where is the update method on the BaseUserManager class?


I have the following class that creates a new user and the user has a m2m object located in the kwargs dict and the update creates this error: 'SomeUser' object has no attribute 'update'.

class SomeUserManager(BaseUserManager):
    def _create_user(self, email, password=None, is_superuser=False, **kwargs):
        if type(kwargs['m2mobject']) is list:
            m2mobject = kwargs['m2mobject'].pop(0)
        user = self.model(email=email, is_superuser=is_superuser, **kwargs)
        if password:
            user.set_password(password)
        user.save()
        user.update(m2mobject=m2mobject)
        return user

    def create_user(self, email, password=None, **kwargs):
        return self._create_user(email, password, is_superuser=False, **kwargs)

    def create_superuser(self, email, password, **kwargs):
        return self._create_user(email, password, is_superuser=True, **kwargs)

I have to remove this m2mobject from kwargs so that the user can be created first and then through this update method I can add the m2m object to the user. Why won't Django just add the m2mobject so I don't have to remove the m2mobject from kwargs? If I don't do this I get this error

Cannot add "m2mobject": instance is on database "None", value is on database "default"

Any help would be appreciated.


Solution

  • update is a method on querysets, not model instances. To add an object to an m2m field, use the add method on the field itself.

    user.m2mobject.add(m2mobject)