Given the following models adapted from http://www.djangoproject.com/documentation/models/generic_relations/
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?
You can’t really do this with generic relations, because there’s nothing to guarantee that the target model will even have an
ediblefield.An alternative is to change the structure to use model inheritance (multi-table). Vegetable and Mineral would both inherit from a
Taggablemodel, which contained theediblefield (or anything else you need to filter on). ThenTaggedItemwould have a standardForeignKeytoTaggable, so you would use the standard double-underscore filter syntax.