2013-12-19 15 views
0

我从一个模型方法返回三个变量,并希望在管理界面上显示它们:变换多个返回值的自定义字符串默认Django管理界面

def time_since(self): 
    time_since = timezone.now() - self.date_opened 
    return time_since.days, time_since.seconds//3600, (time_since.seconds//60)%60 

获得在admin.py

class TicketAdmin(admin.ModelAdmin): 
    list_display = (
    'issue', 
    'time_since', 
    ) 

并且显示为(0,1,21)。我如何将它转换为0天,1:21?

回答

2

假设您已经返回一个元组(0,1,21),则:

x = (0,1,21) 

# Assumes that the values in your tuple will always be an integer. 
s = '{:d} days, {:d}:{:d}'.format(*x) 

print s # 0 days, 1:21 

给出here

编辑字符串格式的文档:在回答您的评论我认为你会调整你的代码返回字符串像这样:

def time_since(self): 
    time_since = timezone.now() - self.date_opened 
    out = [time_since.days, time_since.seconds//3600, (time_since.seconds//60)%60] 

    # As per Aamir Adnan's suggestion check whether day or days is applicable 
    if x[0] == 1: 
     return '{:d} day, {:d}:{:d}'.format(*x) 
    else: 
     return '{:d} days, {:d}:{:d}'.format(*x) 
+0

我在哪里放? – Radolino

+0

这工作,因为是...谢谢 – Radolino

+1

只是一个建议:你可能想检查复数词'天'或不。 '1天'听起来不正确。 –

2

你可以使用django内置模板fil ter timesince另请参见:

from django.template.defaultfilters import timesince_filter 

def time_since(self): 
    return timesince_filter(self.date_opened) # e.g. yield 4 days, 6 hours 
+0

'datetime.timedelta'对象没有属性'year'。为什么?我在谷歌搜索周围,找不到任何相关的东西。 – Radolino

+1

更新了我的答案。你不需要减去日期,因为'timesince_filter'会通过查看你的设置来为你做'TIME_ZONE' –

+0

非常有趣和有用。但对于约会仍然“2小时51分钟”造型。没错,但不是我正在寻找的格式。谢谢 – Radolino