Django:生成CSV文件并将其存储到FileField中 [英] Django: generate a CSV file and store it into FileField
问题描述
在Django View文件中,我需要从元组列表中生成CSV文件,并将该CSV文件存储到模型的FileField中.
In my Django View file, I need to generate a CSV file from a list of tuples and store the CSV file into the FileField of my model.
class Bill(models.Model):
billId = models.IntegerField()
bill = models.FileField(upload_to='bills')
I searched on this site, and found some posts such as Django - how to create a file and save it to a model's FileField?, but the solutions can help me.
我需要将CSV文件存储在"media/bills/"文件夹中,希望该CSV文件可以与Bill对象一起在数据库中删除.
I need the CSV file to be stored in 'media/bills/' fold, and I hope the CSV file can be deleted together with the Bill object in the database.
我尝试了以下代码,但它不能满足我的要求.对于每个文件,它将生成两个文件"output.csv"和"output_xxesss.csv".在这两个文件上,无法通过调用"Bill.objects.all().delete()"来删除.
I tried the following codes, but it cannot meet my requirements. For each file, it will generate two files 'output.csv' and 'output_xxesss.csv'. At the two files cannot be deleted by calling 'Bill.objects.all().delete()'.
path = join(settings.MEDIA_ROOT, 'bills', 'output.csv')
print path
f = open(path, 'w+b')
f.truncate()
csvWriter = csv.writer(f)
csvWriter.writerow(('A', 'B', 'C'))
for r in rs:
print r
csvWriter.writerow(convert(r))
bill = Bill()
bill.billId = 14
bill.bill.save('output.csv', File(f))
bill.save()
谢谢
我尝试了以下代码,但无法通过调用'Bill.objects.all().delete()'删除文件.
I tried the following codes, but it can not delete the file by calling 'Bill.objects.all().delete()'.
bill = Bill()
bill.billId = 14
bill.bill.name = 'bills/output.csv'
bill.save()
推荐答案
删除实例不会删除关联的文件.您可以考虑使用signals
精确地表示pre_delete
.您可以编写一个接收器,在其中可以删除关联的文件.
Deleting an instance would not delete the associated file. You may consider using signals
to be precise pre_delete
. You can write a receiver where in you can delete the associated file.
from django.dispatch import receiver
from django.db.models.signals import pre_delete
@receiver(pre_delete)
def func_name(sender, instance, **kwargs):
your logic
您可以在此处找到文档..
You can find documentation here.
这篇关于Django:生成CSV文件并将其存储到FileField中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!