Get a queryset of objects through an intermediary model

Posted by skyl on Stack Overflow See other posts from Stack Overflow or by skyl
Published on 2009-09-13T14:05:38Z Indexed on 2011/02/02 23:25 UTC
Read the original article Hit count: 341

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...

© Stack Overflow or respective owner

Related posts about django

Related posts about django-models