简体   繁体   English

模型属性django中的简单乘法?

[英]Simple multiplication in model's attribute django?

I am trying to set a default value for attribute threshold in this code, the threshold should be the current level*50 and this is the model 我试图在此代码中为属性阈值设置默认值,阈值应该是当前级别* 50,这是模型

class Level (models.Model):
    name = models.CharField(max_length=20,null=True, blank=True)
    description = models.CharField(max_length=20, null=True, blank=True)
    number = models.IntegerField(null=True, blank=True)
    threshold = models.IntegerField(null=True, blank=True,default=50*number,editable=False)

i get an error unsupported operand types for * : 'int' and 'IntegerField' 我得到unsupported operand types for * : 'int' and 'IntegerField'的错误

You best best is to do such calculation while saving the object. 最好的方法是在保存对象时进行此类计算。 So override Model.save 所以重写Model.save

or a better generic way would be to write a custom field and override pre_save 或者更好的通用方法是编写自定义字段并覆盖pre_save

class DependentIntegerField(models.IntegerField):

    def pre_save(self, model_instance, add):
        if not add: # set the default only while adding model
            return super(self, DependentIntegerField).pre_save(model_instance, add)

        return model_instance.number*50

You can further enhance it and make DependentIntegerField generic so that you can pass callable to it and do any calculation, and you can do further enhancements like checking if user has set the value or not before using default value, and to make it more generic so that you can make any Field as dependent field by passing the field class to a factory function. 您可以进一步增强它并使DependentIntegerField通用的,以便您可以将callable传递给它并进行任何计算,并且您可以进行进一步的增强,例如在使用默认值之前检查用户是否设置了值,并使其更通用通过将字段类传递给工厂函数,可以将任何Field作为依赖字段。 eg 例如

from django.db import models

class_map = {}

def depends_field_pre_save(self, model_instance, add):
    """
    if default is not callable or it is not a model add, lets skip our hook
    """
    if not add or not callable(self.default):
        super(self.__class__, self).__init__(self,*args, **kwargs)
    value = self.default(model_instance)
    setattr(model_instance, self.attname, value)
    return value

def FieldDepends(field_class):
    """
    return a dervied class from field_class which supports dependent default
    """
    if field_class in class_map:
        # we already created this class so return that
        return class_map[field_class]

    new_class = type('Depends'+field_class.__name__, (field_class,), {'pre_save':depends_field_pre_save })

    class_map[field_class] = new_class

    return new_class

and use it like this 并像这样使用它

class DependentModel(models.Model):

    def threshold_default(model_instance=None):
        if model_instance is None:
            return 10
        return model_instance.number*10

    number = models.IntegerField(null=True, blank=True, default=10)
    threshold = FieldDepends(models.IntegerField)(null=True, blank=True, default=threshold_default,editable=False)

I have created a small django project djangodepends on bitbucket with test cases 我在bitbucket上用测试用例创建了一个小的django项目djangodepends

You can override save method to calculation. 您可以覆盖保存方法以进行计算。

https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods

class Level (models.Model):
    name = models.CharField(max_length=20,null=True, blank=True)
    description = models.CharField(max_length=20, null=True, blank=True)
    number = models.IntegerField(null=True, blank=True)
    threshold = models.IntegerField(null=True, blank=True ,editable=False)

    def save(self, *args, **kwargs):
        try:
          self.threshold = self.number * 50
        except TypeError:
          pass
        super(Level, self).save(*args, **kwargs) # Call the "real" save() method.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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