bennedich
bennedich

Reputation: 12367

How do I create a Django model field that evaluates based on other fields?

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)

Upvotes: 1

Views: 1487

Answers (2)

Nathan
Nathan

Reputation: 2995

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.

Upvotes: 0

Ned Batchelder
Ned Batchelder

Reputation: 376052

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

Upvotes: 2

Related Questions