在Django视图中基于整数值返回字符串

时间:2018-07-15 19:41:42

标签: django

我想使用视图函数在django中返回基于某个整数值的字符串值

def picks(request):
    team = get_object_or_404(Team, user=request.user)
    all_picks = team.arr
    pick = team.arr[team.counter]
    return {'pick': pick, 'all_picks': all_picks}

class Team(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    counter = models.IntegerField(default=0)
    total = models.IntegerField(default=1)
    arr = ArrayField(models.IntegerField(blank=True))

那是返回整数值,但我想返回让我们说,如果pick为1,则返回“ Team A”;如果pick为2,则返回“ Team B” 另外计数器的限制是1到5,所以我需要5个条件

1 个答案:

答案 0 :(得分:0)

好,所以我用了字典及其工作方式

def picks(request):
    team = get_object_or_404(Team, user=request.user)
    choices = {1: 'A', 2: 'B', 3: 'C', 4: 'D', 5: 'E'}
    all_picks = team.arr
    pick = choices[team.arr[team.counter]]
    return {'pick': pick, 'all_picks': all_picks}