Django是否可以组合字典值?

时间:2013-11-07 10:01:53

标签: python django

您好我在django中创建了一个测验应用程序。我将数据库检索为json格式,以便在移动应用程序中使用。检索到的json格式为

{

    "quiz": [
        {
            "category": "Python",
            "section": "Programming",
            "qtype": "Mcs",
            "id": 1,
            "level": 0
        },
        {
            "category": "Html",
            "section": "Programming",
            "qtype": "Mc",
            "id": 2,
            "level": 1
        },
        {
            "category": "Php",
            "section": "Theory",
            "qtype": "Yn",
            "id": 3,
            "level": 2
        }
    ]

}

内部列表有三个词典。我想将其转换为

{

    "quiz": [
        {
            "category": "Python -> Programming -> Mcs -> level(0)"
            "id": 1

        },
        {
            "category": "Html -> Programming -> Mc -> level(1)"
            "id": 2
        },
        {
            "category": "Php -> Theory -> Yn -> level(2)"
            "id": 3
        }
    ]

}

是否可以将值转换为字符串?如果是,请分享您的想法。

models.py

class Quiz(models.Model):
    category = models.ForeignKey(Category)
    section = models.ForeignKey(Section)
    qtype = models.ForeignKey(QType)    
    LEVELS = (
        (0,'Beginner'),
        (1,'Intermediate'),
        (2,'Expert'),)
    level=models.IntegerField(default=0, choices=LEVELS)


class Category(models.Model):
    name= models.CharField(max_length=100)


class Section(models.Model):
    name= models.CharField(max_length=100,unique=True)


class QType(models.Model):
    name= models.CharField(max_length=100,unique=True)

views.py

def ajaxdashboard(request):
    quizs=Quiz.objects.all()
    n={'quiz': dict(id=x.id,category=x.category.name,section=x.section.name,qtype=x.qtype.name,level=x.level) for x in quizs]}  
    return HttpResponse(json.dumps(n), mimetype="application/json")

1 个答案:

答案 0 :(得分:0)

当然,只需在视图中生成字符串:

n = {
    'quiz': [
        {
            'id': x.id,
            'category': ' -> '.join([x.category.name, x.section.name, x.qtype.name, 'level({0})'.format(x.level)])
        }
        for x in quizs
    ]
}