django数据集的转换

时间:2018-05-07 07:50:51

标签: python django django-queryset

class Package (models.Model):
    name = models.CharField(max_length=200)

class Package_feature (models.Model):
    category = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=8, decimal_places=2,
        default=Decimal('0.00'))
    package= models.ForeignKey(Package, on_delete=models.CASCADE,
          null=True)

Package的内容如下:

name
set1
set2
set3
set4
set5

Package_feature的内容如下:

  category         price package
'network equip ',  5000, set1
'network equip ',  4000, set2
'network equip ',  3000, set3
'computer equip',  2000, set1
'computer equip',  1500, set2
'computer equip',  1000, set3
'accessories',      200, set4
'accessories',      300, set1
'accessories',      500, set2
'others',           300, set5

我想要制作的是以下数据结构:

  category          set1  set2  set3  set4  set5
'network equip',    5000, 4000, 3000,   -,    -
'computer equip',   2000, 1500, 1000,   -,    -
'accessories',       300,  500,    -, 500,  300

可以使用django查询完成,或者我必须手工编写结果表吗?

1 个答案:

答案 0 :(得分:0)

你可以试试这个。使用distinct()首先获取类别。

然后查询包的名称。

categories = Package_feature.objects.values('category').distinct()
packages = Package.objects.values('name')
package_to_pos = { name:pos for pos,name in enumerate(packages) }
no_of_packages = len(package_to_pos)
result = []
for category in categories: 
    pakages_for_cateogory = Package_feature.objects.filter(category = category)
    prices = ['-']*len(no_of_packages)
    for e in pakages_for_cateogory:
        prices[ package_to_pos[e.package.name] ] = e.price
    result.append( (category,prices) )