user3164429
user3164429

Reputation: 140

Django + Oracle count

I have a questions about count using Django ORM.

Item:

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

Relationship:

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)

Category:

class Category(Item):

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

Product:

class Product(Item):

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

My products are connected to the categories through "Relationship" model, how can I get the number of products in each category or in each set of categories?

Thank you.

Upvotes: 0

Views: 81

Answers (1)

user3164429
user3164429

Reputation: 140

Here is my solution:

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()])

Upvotes: 0

Related Questions