Python将参数传递给可调用函数引用

时间:2021-02-18 23:16:03

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

我不确定我是否以最好的方式提出问题但是,在Django中,我们的模型字段可以有一个默认值,它可以是一个函数

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

示例:(是的,我知道它在上下文中是没有意义的,我知道我可以扩展基类/覆盖save方法)

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.

这应该导致错误,因为my_func需要模型参数,但是我不能在默认情况下调用它,因为它需要一个函数引用并稍后调用它。

Can this be done in Python?

这可以用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

编辑:经过一些研究后,我用lambda想出了这个,不确定逻辑是否正确,对我来说看起来很神奇

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

顺便说一句,Django的AutoField有一个限制,它必须是主键

1 个解决方案

#1


0  

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

您还可以从AutoField继承并通过覆盖check方法来避免调用_check_primary_key。

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)

#1


0  

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

您还可以从AutoField继承并通过覆盖check方法来避免调用_check_primary_key。

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)