views:

40

answers:

2

I'll try to describe my problem with a simple example. Say I have items of type Item and every item relates to a certain type of Category. Now I can take any two items and combine into an itemcombo of type ItemCombo. This itemcombo relates to a certain category called ComboCategory. The ComboCategory is based on which categories the items relate to, therefore I'm not to keen on hardcoding the combocategory in ItemCombo in case the items categories would change. Can I somehow make combocategory a virtual field in ItemCombo that evaluates just in time?

class Category(models.Model):
    value = models.CharField(max_length=1)


class Item(models.Model):
    value    = models.CharField(max_length=10)
    category = models.ForeignKey(Category)


class ComboCategory(models.Model):
    category1 = models.ForeignKey(Category)
    category2 = models.ForeignKey(Category)
    value = models.CharField(max_length=1)


class ItemCombo(models.Model):
    item1         = models.ForeignKey(Item)
    item2         = models.ForeignKey(Item)
    combocategory = models.ForeignKey(ComboCategory)
+1  A: 

Your model classes are full Python classes, so you can add attributes, methods, and properties to them:

class ItemCombo(models.Model):
    item1         = models.ForeignKey(Item)
    item2         = models.ForeignKey(Item)

    @property
    def combocategory(self):
        return .. # some mumbo-jumbo of item1 and item2
Ned Batchelder
I've already tried this and it doesn't solve the problem because I'm not able to do queries this way, for instance filtering all combos of a certain combocategory.
bennedich
Yes, that's right, you can't query on this property. Queries are done against data stored in the database, in the form of fields.
Ned Batchelder
A: 

The issue is that you can only do queries on fields that are stored in the database. Now you should look at aggregation for a way to evaluate your ItemCombo just in time and do filtering on it.

Nathan