简体   繁体   English

__str __()中的rjust()在Django中不起作用

[英]rjust() inside __str__() not working in Django

I have a model class with level and name fields (it's about subcategories levels). 我有一个带有levelname字段的模型类(关于子类别级别)。

I want to display the name of each row with corresponding number of dashes indent in the select dropdown in the admin panel. 我想在管理面板的“选择”下拉列表中显示每行的名称,并带有相应的破折号。

When I use: 当我使用时:

def __str__(self):
    return self.name.rjust((self.level-1) * 4, '-')

in the Django model, it doesn't work and keeps showing me the name without the dashes. 在Django模型中,它不起作用,并不断向我显示名称而不带破折号。

If I use the same code in a pure Python script, it does work. 如果我在纯Python脚本中使用相同的代码,它确实可以工作。 Debug showed that self.level has correct value in the __str__() Django function. 调试显示self.level__str__() Django函数中具有正确的值。

Why it doesn't work in Django? 为什么它在Django中不起作用?

Update: I fixed it with the obvious: 更新:我修复了明显的问题:

def __str__(self):
    indent = '-' * (self.level-1) * 4
    return indent + self.name

However, the question why it doesn't work in Django is still open. 但是,为什么它在Django中不起作用的问题仍然存在。

Your 2 examples aren't the same. 您的两个例子不一样。 rjust doesn't insert the number of fill characters you specify, it inserts the number needed to fill out that total length. rjust不会插入您指定的填充字符数,而是插入填充该总长度所需的数字。 If self.name is long enough, it will be returned unchanged 如果self.name足够长,则将self.name返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM