简体   繁体   English

Django charfield组成默认值

[英]Django charfield compose default value

How can I add a composed default value to a charfield? 如何将组合的默认值添加到charfield?

Example

class Myclass(xxx): class Myclass(xxx):

type = models.ForeignKey(somewhere)
code = models.CharField(default=("current id of MyClass wich is autoincremented + type value"))

Is it possible? 可能吗?

To do so, you override the save method on your model. 为此,您可以覆盖模型上的save方法。

class MyClass(models.Model):
    ...

    def save(self):
        super(Myclass,self).save()
        if not self.code:
            self.code = str(self.id) + str(self.type_id)
            self.save()

There is stuff you need to take care, like making the code a blank field, but you get the idea. 有些东西你需要注意,比如把代码作为一个空白字段,但你明白了。

You should override the save method as Lakshman suggest, however, since this is the default and not blank=False, the code should be a little different: 你应该像Lakshman建议的那样覆盖save方法,但是,因为这是默认值而不是blank = False,所以代码应该有点不同:

Class MyClass(models.Model):
...
def save(self):
    if not self.id:
        self.code = str(self.id) + str(self.type_id)
    return super(Myclass,self).save())

You could also use the post_save signal 您也可以使用post_save信号

from django.db.models import signals

class MyClass(models.Model):
    type = models.ForeignKey(somewhere)
    code = models.CharField(blank=True)

def set_code_post(instance, created, **kwargs):
    instance.code = str(instance.id) + str(instance.type_id)
    instance.save()

signals.post_save.connect(set_code_post, sender=MyClass)

Or, for that matter, you could use a combination of pre_save and post_save signals to avoid running save() twice... 或者,就此而言,您可以使用pre_save和post_save信号的组合来避免运行save()两次...

from django.db.models import signals

class MyClass(models.Model):
    type = models.ForeignKey(somewhere)
    code = models.CharField(blank=True)

def set_code_pre(instance, **kwargs):
    if hasattr(instance, 'id'):
        instance.code = str(instance.id) + str(instance.type_id)

def set_code_post(instance, created, **kwargs):
    if created:
        instance.code = str(instance.id) + str(instance.type_id)
        instance.save()

signals.pre_save.connect(set_code_pre, sender=MyClass)
signals.post_save.connect(set_code_post, sender=MyClass)

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

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