M
M
Mikkkch2020-12-22 16:26:41
Django
Mikkkch, 2020-12-22 16:26:41

Is there a redundant check in the user manager?

Hello, in the Django sources I see the following:

def create_superuser(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True.')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(username, email, password, **extra_fields)

This is the method of the User model manager.
I wrote my manager and in it this method looks like this:
def create_superuser(self, email, password, **extra_fields):
        for field in ['is_staff', 'is_superuser', 'is_active']:
            extra_fields.setdefault(field, True)

            if not extra_fields.get(field):
                raise ValueError(f'Superuser must have {field}=True.')

        return self.create_user(email, password, **extra_fields)

But from all this the question follows, which is that I do not find it expedient to check if not extra_fields.get, expecting True, if we just set the values ​​to True ourselves in the dict. So why did the creators of the frame organize the method in this way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dr. Bacon, 2020-12-22
@Mikkkch

Do you understand exactly how setdefault works?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question