【问题标题】:How to save CSV in database of Django? [closed]如何在 Django 的数据库中保存 CSV? [关闭]
【发布时间】:2019-09-11 04:21:36
【问题描述】:

我制定了一个下载 CSV 文件的逻辑,但现在我还想将其保存在数据库中。

我试过用文件名保存,但是不行

def index(request):
if request.method == "POST":

    url  = request.POST.get('url', '')
    username = request.POST.get('username','')


    r = requests.get(url)           
    soup = BeautifulSoup(r.content, features="lxml")    
    p_name = soup.find_all("h2",attrs={"class": "a-size-mini"})
    p_price = soup.find_all("span",attrs={"class": "a-price-whole"})

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="product_file.csv"'

    for name,price in zip(p_name,p_price):
        writer = csv.writer(response)
        writer.writerow([name.text, price.text])

    return response
    csv_file =  csv.writer(response)   
    csv_save =  csv_save(url=url,username=username,csv_file=csv_file)
    csv_save.save

return render(request, 'index.html')

【问题讨论】:

  • 你有错误的缩进,很难说如果你尝试在return response之后运行代码,它将永远不会被执行。
  • @furas 那么将文件保存在数据库中并同时下载的可能方法是什么
  • 使用 return 作为最后一个命令,因为它结束了函数。
  • 我这样做了,但是得到了这个错误“分配前引用了局部变量'csv_save'”你能告诉我一些代码我怎样才能完成这个任务
  • csv_save(...) 是什么?你试图用你没有创建的这个函数做什么?或者它可能是数据库模型?你是在 Django 中创建这个模型的吗?

标签: python django csv


【解决方案1】:

假设 csv 文件包含:用户名、标题、兴趣。您可以使用具有与 models.py 文件中相同字段的模型将数据保存在数据库中:

class FromCsv(models.Model):    
    username = models.CharField(max_length=200, null=True)
    title = models.CharField(max_length=200, null=True)
    interests = models.CharField(max_length=200, null=True)

然后,您需要遍历 csv 文件的行,将其数据存储在变量中,并使用您的视图保存对象,方法是为每次迭代执行此操作:

FromCsv.objects.create(username=csvusername, title=csvtitle, interests=csvinterests)

由于您似乎想要实际保存 csv 文件,因此您可以在模型上使用 FileField 并执行以下操作:

FromCsv.objects.create(url=url, username=username, csv_file=File(csv_file))

【讨论】:

    【解决方案2】:
        csv_file = csv.writer(response)
        # the object created by calling csv_save can't have the same variable name
        # so we'll call it csv_save_obj to denote it's an instance of csv_save
        csv_save_obj = csv_save(url=url,username=username,csv_file=csv_file)
        # remember to add parenthesis when calling save
        csv_save_obj.save()
    
        # this needs to be at the end, because code after it won't execute
        return response
    

    【讨论】:

    • 谢谢,但此方法返回错误“'_csv.writer' 对象没有属性'_committed'”
    猜你喜欢
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2016-01-13
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2021-02-22
    • 2012-09-17
    相关资源
    最近更新 更多