Get a queryset of objects through an intermediary model
- by skyl
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...