From b6a6787fd857813801dbcd63ac6672da355af998 Mon Sep 17 00:00:00 2001
From: Sergey Fedoseev <fedoseev.sergey@gmail.com>
Date: Thu, 23 Mar 2017 23:27:13 +0500
Subject: [PATCH] [1.11.x] Fixed #27603 -- Fixed AsKML when queryset is
 evaluated more than once.

Backport of e9149d3eb0ed0ddc8b27b1990eb2b7293c1231cd from master
---
 django/contrib/gis/db/models/functions.py | 5 +++--
 tests/gis_tests/geoapp/test_functions.py  | 5 ++++-
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/django/contrib/gis/db/models/functions.py b/django/contrib/gis/db/models/functions.py
index 8a4d54aac1..95eda246ad 100644
--- a/django/contrib/gis/db/models/functions.py
+++ b/django/contrib/gis/db/models/functions.py
@@ -196,8 +196,9 @@ class AsGML(GeoFunc):
 class AsKML(AsGML):
     def as_sqlite(self, compiler, connection):
         # No version parameter
-        self.source_expressions.pop(0)
-        return super(AsKML, self).as_sql(compiler, connection)
+        clone = self.copy()
+        clone.set_source_expressions(self.get_source_expressions()[1:])
+        return clone.as_sql(compiler, connection)
 
 
 class AsSVG(GeoFunc):
diff --git a/tests/gis_tests/geoapp/test_functions.py b/tests/gis_tests/geoapp/test_functions.py
index 61ae7dc9a6..56ba63673b 100644
--- a/tests/gis_tests/geoapp/test_functions.py
+++ b/tests/gis_tests/geoapp/test_functions.py
@@ -122,8 +122,11 @@ class GISFunctionsTests(TestCase):
             City.objects.annotate(kml=functions.AsKML('name'))
 
         # Ensuring the KML is as expected.
-        ptown = City.objects.annotate(kml=functions.AsKML('point', precision=9)).get(name='Pueblo')
+        qs = City.objects.annotate(kml=functions.AsKML('point', precision=9))
+        ptown = qs.get(name='Pueblo')
         self.assertEqual('<Point><coordinates>-104.609252,38.255001</coordinates></Point>', ptown.kml)
+        # Same result if the queryset is evaluated again.
+        self.assertEqual(qs.get(name='Pueblo').kml, ptown.kml)
 
     @skipUnlessDBFeature("has_AsSVG_function")
     def test_assvg(self):