将字典列表转换为Django可访问对象

时间:2019-04-18 09:08:00

标签: django django-views

我正在像这样的Django函数中执行SQL查询:

cursor.execute('''Select * from classroom_quiz as cq, classroom_activetruck as ca
                        where cq.origin=ca.origin and cq.destination=ca.destination and cq.subject_id=ca.subject_id and cq.total_trucks<=ca.total_trucks;''')
    invoices = dictfetchall(cursor)

这给我以下形式的输出:

[{'id': 15, 'name': 'test', 'origin': '0', 'destination': '0', 'total_trucks': 7, 'material_type': 'Fragile', 'scheduled_date': '0', 'offered_price': 0, 'owner_id': 1, 'subject_id': 1},
{'id': 1, 'name': 'truck', 'origin': '0', 'destination': '0', 'total_trucks': 5, 'material_type': 'Fragile', 'scheduled_date': '0', 'offered_price': 0, 'owner_id': 1, 'subject_id': 1}]

如何使用此元组列表,以便可以将其投影到应用程序的输出屏幕上? 我能想到的一种方法是将其转换为django对象,但这只是预感。

Models.py

class Quiz(models.Model):

    mtypes =(('Fragile','Fragile'),('Non-Fragile','Non-Fragile'))

    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='quizzes')
    name = models.CharField(max_length=255)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='quizzes')
    origin = models.CharField(max_length=255, default=0)
    destination = models.CharField(max_length=255,default=0)
    total_trucks = models.IntegerField(default=0)
    material_type = models.CharField(max_length=255,default=0, choices=mtypes)
    scheduled_date = models.CharField(max_length=255,default=0)
    offered_price = models.IntegerField(default=0)



    def __str__ (self):
        return self.name


class Activetruck(models.Model):

    # mtypes =(('Fragile','Fragile'),('Non-Fragile','Non-Fragile'))

    owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='activetruck')
    name = models.CharField(max_length=255)
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='activetruck')
    origin = models.CharField(max_length=255, default=0)
    destination = models.CharField(max_length=255,default=0)
    total_trucks = models.IntegerField(default=0)
    # material_type = models.CharField(max_length=255,default=0, choices=mtypes)
    scheduled_date = models.CharField(max_length=255,default=0)
    offered_price = models.IntegerField(default=0)

    def __str__ (self):
        return self.name

0 个答案:

没有答案