I apologize in advance if this is not the correct area to post this, but I can't seem to find any help in the docs or on Stack Overflow. TastyPie is awesome, and I've been able to get very close to the desired XML output. However, the problem arises when I want to have a custom attribute on a node. I can't seem to find a way to do this with TastyPie barring writing the API from scratch.
For example let's say I have this sample output from TastyPie (excerpt only):
<media type="list">
<object type="hash">
<filename>filename.mp4</filename>
<id type="integer">62</id>
<name>AE</name>
<position type="integer">0</position>
<product type="integer">65</product>
<type>video</type>
</object>
<object type="hash">
<filename>filename.jpg</filename>
<id type="integer">63</id>
<name>Some Name</name>
<position type="integer">1</position>
<product type="integer">65</product>
<type>image</type>
</object>
</media>
What I really need is this (notice I want to add a custom attribute (or attributes) to a node - in this case, filename has a attribute):
<media type="list">
<object type="hash">
<filename type="video">filename.mp4</filename>
<id type="integer">62</id>
<name>Some Name</name>
<position type="integer">0</position>
<product type="integer">65</product>
</object>
<object type="hash">
<filename type="image">filename.jpg</filename>
<id type="integer">63</id>
<name>Another Name</name>
<position type="integer">1</position>
<product type="integer">65</product>
</object>
</media>
Or even better, this:
<media type="list">
<object type="hash" format="video" id="62" position="0" product_type="65" filename="filename.mp4" name="Some Name" />
<object type="hash" format="image" id="63" position="1" product_type="65" filename="filename.jpg" name="Another Name" />
</media>
What would be required in order to customize the XML serializer to add attributes where needed? Or even better, tell it which values can be safely described as attributes rather than as a node? I don't understand how to add an attribute to the output XML. Any help is greatly appreciated. Thanks in advance.
Well I got my answer, but not on my own. Thanks to Omelyanyk Andrey in Poland for this working code...this got me to where I need to be and allows me to further customize now that I have working code to learn from.
class MySerializer(Serializer):
def format_datetime(self, data):
return utc_to_est_human(data)
def format_date(self, data):
return data.strftime("%Y-%m-%d")
def to_xml(self, data, options=None):
"""
Given some Python data, produces XML output.
"""
options = options or {}
if lxml is None:
raise ImproperlyConfigured("Usage of the XML aspects requires lxml and defusedxml.")
etree = self.to_etree(data, options)
for element in etree.xpath('//media/object'):
for child in element.getchildren():
element.set(child.tag, child.text)
element.remove(child)
return tostring(etree, encoding='utf-8')