Ian Cohen
Ian Cohen

Reputation: 576

Django - filtering on generic related objects

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?

Upvotes: 0

Views: 1094

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

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.

Upvotes: 1

Related Questions