views:

82

answers:

2

I want get all of the Geom objects that are related to a certain content_object (see the function I'm trying to build at the bottom, get_geoms_for_obj()

class Geom(models.Model):
    ...

class GeomRelation(models.Model):
    ''' For tagging many objects to a Geom object and vice-versa'''

    geom = models.ForeignKey(Geom)
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey()

def get_geoms_for_object(obj):
    ''' takes an object and gets the geoms that are related

    '''
    ct = ContentType.objects.get_for_model(obj)
    id = obj.id
    grs = GeomRelation.objects.filter( content_type=ct, object_id=id )
    # how with django orm magic can I build the queryset instead of list
    # like below to get all of the Geom objects for a given content_object
    geoms = []
    for gr in grs:
        geoms.append(gr.geom)
    return set(geoms)
    # A set makes it so that I have no redundant entries but I want the
    # queryset ordering too .. need to make it a queryset for so many reasons...
+1  A: 

Duh,

return Geom.objects.filter(geomrelation__in=grs)
skyl
still if anyone has anything to add or any objections or comments, I'll leave this open for a bit.
skyl
+1  A: 

If your Geom class has a generic.GenericRelation() property, you can get the objects via a standard backwards relation.

class Geom(models.Model):
    ...
    geom_relations = generic.GenericRelation(GeomRelation)

This is Python-only property, which doesn't need a database change. Now to get the geom_relations, you just do:

geom.geom_relations.all()
Daniel Roseman