Django ORM查询或列表字典

时间:2015-12-03 10:53:40

标签: python sql django dictionary orm

问题是如何从三个模型进行查询并输出为一个字典。下面用代码进行更多解释。

模型

class AdvertCategory(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    name = models.CharField(max_length=255, db_index=True)
    ts = models.DateTimeField(auto_now=True, blank=True)

    def __str__(self):
        return self.name


class AdvertSubcategory(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    name = models.CharField(max_length=255, db_index=True)
    category = models.ForeignKey('AdvertCategory',db_index=True)

    def __str__(self):
        return self.name

class CategoryImage(models.Model):
    id = models.AutoField(primary_key=True, db_index=True)
    image = models.ImageField(upload_to='category_image', db_index=True, blank=True, null=True)
    category = models.ForeignKey('AdvertCategory',db_index=True)

    def __str__(self):
        return str(self.category)

的观点

subcategory = AdvertSubcategory.objects.values('id','name','category')

    data = []

    for z in subcategory:
        data.append({
            'subcategory':z['name'],
            'category':AdvertCategory.objects.get(id=z['category']).name
        })

    data2 = []

    category = AdvertCategory.objects.values('id','name')
    for p in category:
        data2.append({
            'image':CategoryImage.objects.get(category=p['id']).image,
            'category':p['name']
        })


    lst = sorted(itertools.chain(data,data2), key=lambda x:x['category'])
    list_c = []
    for k,v in itertools.groupby(lst, key=lambda x:x['category']):
        d = {}
        for dct in v:
            d.update(dct)
        list_c.append(d)
    print list_c

逻辑是获得所有类别 - >名称,并根据AdvertsSubcategory中的类别 id 选择所有子类别。然后根据类别 id 获取CategoryPicture。 简单的输出就像:

data = [{   'category':'Auto moto aero i nautika',
            'image':'../images/picture.png',
            'subcategory':'Aero',
            'subcategory':'Autoškola',
            'subcategory':'Najam cestovnih vozila, bicikala i plovila',
            'subcategory':'Nautika i nautička oprema',
            'subcategory':'Oprema, servis, dijelovi i usluge',
            'subcategory':'Predstavništvo i prodaja',
            'subcategory':'Teretna vozila, servis i dijelovi',
            'subcategory':'Vulkanizeri, elektrika i akumulatori'
         }]

是否有简单的方法可以使用ORM或列表?

0 个答案:

没有答案