I have this code from Kohana (it's easily understandable) and I want to convert this to Django ORM given the ff. models:
class Item(models.Model):
glasses = models.ManyToManyField(Glass, through="ItemGlass")
collection = models.ForeignKey(Collection)
class ItemGlass(models.Model):
glass = models.ForeignKey(Glass)
item = models.ForeignKey(Item)
class Collection(models.Model):
name = models.CharField(max_length=100)
class Code(models.Model):
code = models.CharField(max_length=30)
description = models.TextField()
class Glass(models.Model):
collection = models.ForeignKey(Collection)
code = models.ForeignKey(Code)
and the php query (uses Kohana's Database Lib)
$this->select(
array('cd.id', 'id'),
array('cd.description','description'),
array('COUNT(DISTINCT("items.id"))', 'count')
)
->from('items')
->join(array('collections', 'c'))
->on('c.id', '=', 'items.collection_id')
->join(array('glasses', 'g'))
->on('g.collection_id', '=', 'c.id')
->join(array('code', 'cd'))
->on('cd.id', '=', 'g.code_id')
->where('items.discontinued', '=', FALSE)
->group_by('cd.id');
NOTE: the "array" clause you see is translated as
"SELECT cd.id AS id, cd.description AS description, COUNT(DISTINCT(items.id) AS count"
The thing is how do I do it? I can't successfully use select_related to join multiple tables in this case, and I can't find a good "filter trick" for the query. Any ideas?
EDIT: I am considering doing it in plain SQL, but I would prefer to avoid it if a Django ORM query can be done :)
ItemGlassmodel? Are the more attributes on it that you left out for simplification?