Django实例 - 在模型中组合两个属性值

时间:2015-11-12 02:43:16

标签: django 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)

我想结合fn_id,ln_id和pn_id,并将三个值的组合保存到字段标题中。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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)

让我们阅读这篇文章:https://docs.djangoproject.com/en/1.8/ref/models/fields/#onetoonefield