Commits

Gianluca Pacchiella  committed 66faae9

Allow to pass an Address instance as argument of easy_map tag.

This reduce the database hits since we can pass directly the instance
instead of its description.

  • Participants
  • Parent commits 8c0aef5

Comments (0)

Files changed (2)

File easy_maps/templatetags/easy_maps_tags.py

     """
     The syntax:
         {% easy_map <address> [<width> <height>] [<zoom>] [using <template_name>] %}
+
+    The "address" parameter can be an Address instance or a string describing it.
+    If an address is not found a new entry is created in the database.
     """
     width, height, zoom, template_name = None, None, None, None
     params = token.split_contents()
             address = self.address.resolve(context)
             template_name = self.template_name.resolve(context)
 
-            map = None
-            if address == '':
-                map = Address(latitude=settings.EASY_MAPS_CENTER[0], longitude=settings.EASY_MAPS_CENTER[1])
-            else:
-                map, _ = Address.objects.get_or_create(address=address)
+            map = address
+            if not isinstance(address, Address):
+                if address == '':
+                    map = Address(latitude=settings.EASY_MAPS_CENTER[0], longitude=settings.EASY_MAPS_CENTER[1])
+                else:
+                    map, _ = Address.objects.get_or_create(address=address)
 
             context.update({
                 'map': map,

File easy_maps_tests/test_app/tests.py

 
         self.assertEqual(n_addresses_after, n_addresses_before + 1)
 
+    @override_settings(EASY_MAPS_CENTER=fake_default_center)
+    def test_use_address_instance(self):
+        """It's possible to pass directly to the easy_map tag an Address instance.
+
+        This test checks also that the database is not hit.
+        """
+        # create a fake address
+        Address.objects.create(address='fake')
+        n_addresses_before = len(Address.objects.all())
+
+        simple_template_string = """{% load easy_maps_tags %}
+        {% easy_map address 500 500 10 %}
+        """
+        address = Address.objects.all()[0]
+        t = Template(simple_template_string)
+        # this assert works only from django1.3
+        self.assertNumQueries(0, lambda: t.render(Context({'address': address,})))
+
+        n_addresses_after = len(Address.objects.all())
+
+        # no Address is created in the process
+        self.assertEqual(n_addresses_after, n_addresses_before)