循环显示两个查询集,同时突出显示django中的差异

时间:2011-09-30 10:47:10

标签: django django-templates django-queryset

我有一个如下定义的模型类:

class Vehicle(models.Model):
    stock_number = models.CharField(max_length=6)
    vin = models.CharField(max_length=17)
    year = models.PositiveSmallIntegerField()
    manufacturer = models.CharField(max_length=15)
    manufacturer_popularity = models.CharField(max_length=1, blank=True, null=True)
    model = models.CharField(max_length=20)
    series = models.CharField(max_length=35, blank=True, null=True)
    exterior_colour = models.CharField(max_length=25)
    interior_colour = models.CharField(max_length=25)
    interior_type = models.CharField(max_length=25)
    doors = models.PositiveSmallIntegerField()
    passengers = models.PositiveSmallIntegerField()
    body_style = models.CharField(max_length=30)
    transmission = models.CharField(max_length=50)
    fuel_type = models.CharField(max_length=50)
    engine_capacity = models.DecimalField(max_digits=2, decimal_places=1)
    cylinders = models.PositiveSmallIntegerField()
    drive_train = models.CharField(max_length=50)

我想要做的是根据上面的类查询两个数据库,然后在模板中显示数据,同时以红色显示每个配对的Vehicle条目之间的差异。查询位不是我猜的主要问题,因为我需要类似的东西:

set1 = Vehicle.objects.all()
set2 = Vehicle.objects.using('other_db').all()

但是如何处理配对和显示?我希望有人能告诉我这里的亮点。

更新1

vehicles = []
for v1 in set1:
    for v2 in set2:
        if v1['stock_number'] == v2['stock_number']:
            vehicle1 = vehicle2 = {}
            vehicle1['vehicle_1'] = v1
            vehicle2['vehicle_2'] = v2
            vehicles.append(vehicle1)
            vehicles.append(vehicle2)
        else:
            vehicle1 = vehicle2 = {}
            vehicle1['vehicle_1'] = v1
            vehicle2['vehicle_2'] = {}
            vehicles.append(vehicle1)
            vehicles.append(vehicle2)

1 个答案:

答案 0 :(得分:1)

想法

from itertools import izip

for obj1, obj2 in izip(set1, set2):
    for field in obj1._meta.fields:
        if field.value_from_object(obj1) == field.value_from_object(obj2):
            print 'Same value', field.value_from_object(obj1)
        else:
            print 'Obj1 has', field.value_from_object(obj1)
            print 'Obj2 has', field.value_from_object(obj2)