Example #1
0
    def test_generic_relations(self):
        """
        Check that get_generic_relations correctly populates the
        _content_object_cache of each element with a GenericForeignKey, in fewer
        queries than simply iterating through and checking x.content_object.
        """
        assets = Asset.objects.all()
        related_items = set([a.content_object for a in assets])
        # needed 1 query to get assets, 2 for contenttypes (article and gallery)
        # and 200 for the actual items (even though there are only 40)
        self.assertEquals(len(connection.queries), 203)
        self.assertEquals(len(related_items), 40)

        reset_queries()
        ContentType.objects.clear_cache()
        get_generic_relations(assets)
        for asset in assets:
            self.assertTrue(hasattr(asset, '_content_object_cache'))
            self.assertEquals(asset.content_object.id, asset.object_id)
        # should have one query to get the contenttypes, then one per type
        self.assertEquals(len(connection.queries), 3)

        self.assertRaises(RelationNotFound, get_generic_relations, assets,
                          'nonexistentrelationship')
def resolve_generics(queryset, relation_name=None):
    if relation_name is not None:
        utils.get_generic_relations(queryset, relation_name)
    else:
        utils.get_generic_relations(queryset)
    return ''