zab aluj
zab aluj

Reputation: 45

How to concatenate model field values in pre_save Django

I don't know how to ask this question so please bear with me.

Here is my problem:

I have two models Foo and Bar. Following is it's models.py,

class Foo(models.Model):
    foo_code = models.CharField(max_length=12, blank=True, null=True)


class Bar(models.Model):
    foo_rel = models.ForeignKey(Foo)
    bar_code = models.CharField(max_length=12, blank=True, null=True)

Now, foo_code is let say 123456 then I when I am creating new Bar instance I want bar_code to be {{foo_code}}-{{id of Bar}}, i.e. 123456-01.

I am not able get my way around. I thought of using pre_save/post_save but can't think of logic. Please help!

EDIT: added FK to Foo

Upvotes: 1

Views: 534

Answers (1)

user8060120
user8060120

Reputation:

You can override the save method:

class Bar(models.Model):
    foo_rel = models.ForeignKey(Foo)
    bar_code = models.CharField(max_length=12, blank=True, null=True)

    def save(self, *args, **kwargs):
        if self.bar_code and len(self.bar_code.split('-')) > 1:
            # Do update the Bar instance, need remove old previx first
            self.bar_code = self.bar_code.split('-')[1]
        self.bar_code = '{}-{}'.format(self.foo_rel.foo_code, self.bar_code)
        super(Bar, self).save(*args, **kwargs)

this will work as follows:

>>> f = Foo.objects.create(foo_code='123456')
>>> b = Bar.objects.create(foo_rel=f, bar_code='01')
>>> b.bar_code
u'123456-01'
>>> b.bar_code = '03'
>>> b.save()
>>> b.bar_code
u'123456-03'
>>> f.foo_code = '4567'
>>> f.save()
>>> b.save()
>>> b.bar_code
u'4567-03'

and it's looks good, but you should remember it will not work on bulk update:

>>> Bar.objects.update(bar_code='333')
1
>>> b.refresh_from_db()
>>> b.bar_code
u'333'

Upvotes: 1

Related Questions