I'm stuck with this as I can't find any relevant tutorials online. I would like to
- export all of the data in a model to the txt file format {actually xml but I think that's besides the point}
- where each row in the model is a seperate file
- and saved to a relative local path to the database
- with the folder and filenames for each being derived from two fields in the model
- I also need these to replace any existing files of the same name
Where would I start? All I can do currently is export a txt file with all records together as a downloadable attachment.
This is what the code would like if I were presenting it as a HTML page, however of course the filename and folder fields are not referenced.
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<movie>
<plot />
<outline />
<title>{{ misc.title }}</title>
<release date>{{ misc.d_released }}</release date>
</fileinfo>
</movie>
Here are the fields
class misc(models.Model):
d_created = models.DateTimeField(auto_now_add=True)
filename = models.CharField(max_length=250)
folder = models.ForeignKey(folder, default="1", blank=True, null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=250, default='', blank=True, null=True)
d_released = models.CharField(max_length=25, default='', blank=True, null=True)
description = models.TextField(blank = True, null = True)
def __str__(self):
return self.title
class Meta:
ordering = ('-id', )
CodePudding user response:
Seems like you don't need Django for this task (maybe).
UPD:
Use CSV!
Your Excel could export data into a .csv file - this is a very simple format and very easy to start with Python.
Place your .csv near you python script otherwise provide a full path to the file:
import csv
with open('file.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
print(', '.join(row))
So check that you can read the data of your rows. Docs
Next, let's make a handler for your rows:
Here you can use XML builder but this is not a quick way. Let's make something like a text template and replace the needed macros with your row's values as you defined in the beginning.
f`text {param}`
Finally, how to write this to the filesystem? Easy!
First, how to create a dir or nested dirs? A good thread here:
How can I safely create a nested directory?
So create a needed dir and then you can concatenate dir needed filename to create a file:
with open("full_path_to_future_file.xml", "w") as f:
f.write(rendered_xml_as_text)
All these stuff you can do when iterating in your
for row in reader: cycle, of course.
Call your script like python script.py and task solved!
