Query with parameter

Asked

Viewed 62 times

1

I’m watching a video python but I didn’t understand one thing.

I have the file utils.py

def code_generator(size=6, chars=string.ascii_lowercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def create_shortcut(instance, size = 6):
    new_code = code_generator(size = size)
    Klass = instance.__class__
    qs_exists = Klass.objects.filter(shortcode=new_code).exists()
    if qs_exists:
        return create_shortcut(size = size)
    return new_code

Model file.py

def save(self, *args, **kargs):
   if self.shortcode is None or self.shortcode == "":
       self.shortcode = create_shortcut(self)
   super(KirrURL, self).save(*args, **kargs)

In the model.py file the call is made create_shortcut(self) which I understood, which is passed to the class itself, and was not informed the parameter size which is default 6.

However, here in utils.py:

 if qs_exists:
    return create_shortcut(size = size)

In the above section it would not have to be return create_shortcut(instance, size = size)? Because the parameter was not passed instance again?

1 answer

2


This - I didn’t see the video with audio, but yes, this code is wrong. The parameter instance is mandatory and is not passed on - maybe it was an example of code created by live while the video was made, and therefore subject to errors.

What happens is that as the error expression is inside an "if" it may be that in cases that it has tested live it has never run, and then the error did not appear.

  • I changed the code to pass in that condition and gave the error: create_shortcut() Missing 1 required positional argument: 'instance'. Thanks, I had been very confused by the lack of argument, because of the "self" that need not inform, I thought in this case would be something like

Browser other questions tagged

You are not signed in. Login or sign up in order to post.