2014-01-19 36 views
0

我對使用Django ORM計數有疑問。Django + Oracle計數

項目:

class Item(models.Model): 
    member = models.ManyToManyField('self', through='Relationship', symmetrical=False, null=True, blank=True) 

關係:

class Relationship(models.Model): 
    parent = models.ForeignKey(Item, related_name='p2c') 
    child = models.ForeignKey(Item, related_name='c2p') 

    TYPE_OF_RELATIONSHIP = (
     ('rel', 'Relation'), 
     ('hier', 'Hierarchy'), 
    ) 
    type = models.CharField(max_length=10, choices=TYPE_OF_RELATIONSHIP, null=False, blank=False) 

類別:

class Category(Item): 

    def __str__(self): 
     return self.getName() 

產品:

class Product(Item): 

    def __str__(self): 
     return self.getName() 

我的產品通過「關係」模型與類別相關聯,如何獲得每個類別或每個類別的產品數量?

謝謝。

回答

0

這裏是我的解決方案:

def getCountofproducts(list): 
    #list - category ids 

    where = '"{0}"."{1}" = "CORE_RELATIONSHIP"."CHILD_ID"'.format(Product._meta.db_table, Product._meta.pk.column) 
    table = '"{0}"'.format(clsObj._meta.db_table) 

    return Category.objects.filter(p2c__parent_id__in=list, p2c__type="rel", p2c__child_id__isnull=False)\ 
            .values('p2c__parent').annotate(childCount=Count('p2c__parent'))\ 
            .extra(tables=[table], where=[where.upper()])