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



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

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)

创意

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)

相关内容

  • 没有找到相关文章

最新更新