maumercado
maumercado

Reputation: 1473

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?

Upvotes: 1

Views: 3508

Answers (3)

Conor
Conor

Reputation: 105

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)

Upvotes: 0

Liorsion
Liorsion

Reputation: 582

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())

Upvotes: 2

lprsd
lprsd

Reputation: 87077

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.

Upvotes: 2

Related Questions