简体   繁体   中英

Python pass arguments to callable function reference

I am not sure if I worded the question the best way but, in Django, our model fields can have a default value, which can be a function

Example : (Yes I know it is pointless in context, and I know I can extend the base class/overwrite the save method)

class MyModel(models.Model):
    #How do i pass an argument without calling it
    model_name = models.IntegerField(default=my_func)


def my_func(model):
    return model.__name__

This should result in an error as my_func expects the model parameter, but I can't call it in the default because it expects a function reference and will call it later.

Can this be done in Python?

Edit: After some more research I came up with this using lambda, not sure if the logic is correct, it looks like magic to me

def auto_field(model):
    last_id = model.objects.latest('cod')
    if last_id is not None:
        return last_id + 1
    return 1

class MyModel(models.Model):
    uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    cod = models.IntegerField(default=lambda: auto_field(self), editable=False, unique=True)

By the way, Django's AutoField has a limitation that it has to be the primary-key

You also can inherit from AutoField and avoid the call to _check_primary_key by overriding the check method.

class MyAutoField(models.AutoField):
    def check(self, **kwargs):
        errors = models.Field.check(**kwargs)
        # errors.extend(self._check_primary_key())
        return errors

class MyModel(models.Model):
    uid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    cod = MyAutoField(editable=False, unique=True)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM