Iam Moon
Iam Moon

Reputation: 695

Django instance - Combine two attribute values in model

Can someone tell me how to combine two or more attribute values of in another field by using instance?

Models.py:

    fn_id = models.ForeignKey(FilemNumber, null=True, blank=True)
    ln_id = models.ForeignKey(LineNumber, null=True, blank=True)
    pn_id = models.ForeignKey(PhotoNumber, null=True, blank=True)

    title = models.CharField(max_length=255,blank=True, null=True)

I want to combine fn_id, ln_id and pn_id and save the combination of the three values into field title.

Upvotes: 0

Views: 400

Answers (1)

Vuong Hoang
Vuong Hoang

Reputation: 149

You can do this:

from django import models

class BaseModel(models.Model):
    fn_id = models.ForeignKey(FilemNumber, null=True, blank=True)
    ln_id = models.ForeignKey(LineNumber, null=True, blank=True)
    pn_id = models.ForeignKey(PhotoNumber, null=True, blank=True)


class YourModel(models.Model):
    common = models.OneToOneField(BaseModel)

    # I suppose that you want to get title, so let define title method
    # if obj is an instance of YourModel, you can access title like this:
    # obj.title
    @property
    def title(self):
        return '{}{}{}{}'.format(self.id, self.common.fn_id,
                                 self.common.ln_id, self.common.pn_id)

Lets read this article: https://docs.djangoproject.com/en/1.8/ref/models/fields/#onetoonefield

Upvotes: 2

Related Questions