Curly brackets added to the result of subclass of Func

Hey,
I created my own subclass of Func, just to simplify the XPath queries. Implementation is simple:

class XPath(Func):
    function = 'xpath'
    output_field=CharField()
    template = '''%(function)s(%(expressions)s, ARRAY[
		ARRAY['ns1',' namespace1'], 
		ARRAY['ns2', 'namespace2']
	])'''

I’m calling it using annotate, exactly this way:

Entity.objects.annotate(
                extracted_value=XPath(
                    Value('ns1:root/ns1:lev1/ns1:lev2/ns1:lev2/ns1:lev4/ns1:lev5/text()'), 
                    'xml_message'
                )
            ).values_list('entity_id','extracted_value').get(entity_id=947470)

It properly produces sql query:

SELECT 
	"entity"."entity_id", 
	xpath('ns1:root/ns1:lev1/ns1:lev2/ns1:lev2/ns1:lev4/ns1:lev5/text()', "entity"."xml_message", ARRAY[
		ARRAY['ns1',' namespace1'], 
		ARRAY['ns2', 'namespace2']
	]) AS "extracted_value" 
FROM 
	"entity" 
WHERE 
	"entity"."entity_id" = 947470

Query executed in SQL console gives result “12345”, however when executed via model, for example in test cases:

self.assertEqual('12345', Entity.objects.annotate(
                extracted_value=XPath(
                    Value('ns1:root/ns1:lev1/ns1:lev2/ns1:lev2/ns1:lev4/ns1:lev5/text()'), 
                    'xml_message'
                )
            ).values_list('entity_id','extracted_value').get(entity_id=947470)[1])

it shows:

E       AssertionError: '12345' != '{12345}'
E       - 12345
E       + {12345}
E       ? +     +

My question is: why is that? Did i do something wrong/missconfigured Func?

The return value of the Postgres xpath function (I assume you are using Postgres because of the ARRAY construct) is entirely dependent on the structure of the queried XML document which you haven’t provided so it will pretty hard for anyone to help you.

My guess is that the xpath function can return arrays of results depending on the queried data and because you haven’t added django.contrib.postgres to your INSTALLED_APPS what is returned to you is '{12345}' instead of [12345] where the former is the string representation of arrays on Postgres.

You’re the star! Correct answer! Unnest resolves the situation, I know per the XML schema only one element can be returned.