简体   繁体   中英

Django charfield compose default value

How can I add a composed default value to a charfield?

Example

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.

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:

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

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...

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)

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