1

嗨,我正在 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
        }
    ]

}

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

模型.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)

视图.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")
4

1 回答 1

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
    ]
}  
于 2013-11-07T10:05:59.040 回答