views:

93

answers:

1

Given the following models adapted from http://www.djangoproject.com/documentation/models/generic%5Frelations/

class TaggedItem(models.Model):
    """A tag on an item."""
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

class Vegetable(models.Model):
    name = models.CharField(max_length=150)
    is_yucky = models.BooleanField(default=True)
    edible = models.BooleanField(default=True)

class Mineral(models.Model):
    name = models.CharField(max_length=150)
    hardness = models.PositiveSmallIntegerField()
    edible = models.BooleanField(default=True)

How would I filter TaggedItems so that I get only those with content_objects that are edible?

ideally, something like:

TaggedItem.objects.filter(content_object.edible=True)



What if Vegetable and Mineral had is_edible methods?

+1  A: 

You can't really do this with generic relations, because there's nothing to guarantee that the target model will even have an edible field.

An alternative is to change the structure to use model inheritance (multi-table). Vegetable and Mineral would both inherit from a Taggable model, which contained the edible field (or anything else you need to filter on). Then TaggedItem would have a standard ForeignKey to Taggable, so you would use the standard double-underscore filter syntax.

Daniel Roseman