def __str__在模型上

时间:2018-07-11 04:45:07

标签: django django-models

我希望在此模型上返回等于行业名称+风险水平(即低)的str

RISKLEVEL = (
    (0, "Low"),
    (1, "Medium"),
    (2, "High"),
    )

class IndustryIndex(models.Model):
    industry = models.CharField(max_length=200)
    risk = models.IntegerField(choices=RISKLEVEL)
    description = models.CharField(max_length=200)

    def __str__(self):
        return self.industry + self.page

我知道def __str__(self):下一行的语法不正确。你知道应该是什么吗?另外,self.page似乎只返回整数,但是我对返回描述(即'High')很感兴趣。

谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用get_risk_display()方法:

class SchoolDistrict(TimeStampMixin, Address):
    __tablename__ = 'school_district'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(200), nullable=False)
    slug = db.Column(db.String(250), nullable=False, unique=True)

    @staticmethod
    def before_insert(mapper, conn, target):
        if not target.slug:
            target.slug = slugify(target.name)

    @staticmethod
    def before_update(mapper, conn, target):
        print(slugify(target.name))
        target.slug = slugify(target.name)
        print(target.slug)

    def for_user(self):
        dict_ = super().for_user()
        dict_['name'] = self.name
        dict_['slug'] = self.slug
        return dict_

    def __str__(self):
        return self.name

db.event.listen(SchoolDistrict, 'before_insert', SchoolDistrict.before_insert)
db.event.listen(SchoolDistrict, 'before_update', SchoolDistrict.before_update)