I'm exporting all product details from db to an XML file. One of the fields need to export is images. There are two fields where images should be exported. If there is one image (product table) should be exported to item_image_link
. If there are more than one (ProductImage table) to item_additional_image_link
.
products = Product.objects.filter(product_status=True).prefetch_related('images')
for product in products:
item = ET.SubElement(channel, "item")
g_item_id = ET.SubElement(item, ("{http://base.google.com/ns/1.0}id")).text = product.sku
g_item_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}image_link")).text = 'http://127.0.0.1:8000' products.image.url
for image in product.images.all():
g_item_additional_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}additional_image_link")).text = 'http://127.0.0.1:8000' image.image.url
I successfully export the images per product in the respective field item_additional_image_link
however they are shown in three different lines according to the number of images in db.
<item>
<g:id>55555</g:id>
<g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/K003-min.jpeg</g:additional_image_link>
<g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/K009-min.jpeg</g:additional_image_link>
<g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/image00024-min.jpeg</g:additional_image_link>
</item>
How can i make the three lines above in one, comma separated between each image? Something like:
<item>
<g:id>55555</g:id>
<g:additional_image_link>http://127.0.0.1:8000/media/photos/2021/12/20/K003-min.jpeg, http://127.0.0.1:8000/media/photos/2021/12/20/image00024-min.jpeg, http://127.0.0.1:8000/media/photos/2021/12/20/K009-min.jpeg</g:additional_image_link>
</item>
Thank you
CodePudding user response:
Build the values before creating an ET.SubElement(...)
additional_image_links = ",".join([f"http://127.0.0.1:8000{x.image.url}" for x in product.images.all()])
if additional_image_links:
g_item_additional_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}additional_image_link")).text = additional_image_links
CodePudding user response:
You need to use the string method .join
on the multiple text fields to join them into one, then generate a single XML element. I'm guessing about ET...
g_item_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}image_link")
).text = 'http://127.0.0.1:8000' products.image.url
texts = []
for image in product.images.all():
texts.append( 'http://127.0.0.1:8000' image.image.url )
if texts: # don't generate an empty element
g_item_additional_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}additional_image_link")
).text = ', '.join( texts)