Django - 如何在模型保存期间添加文件?

时间:2017-12-24 12:06:06

标签: django django-models

我尝试创建并保存csv文件作为保存的一部分,然后将文件关联到记录。

这是我的模特

class ReOrder (models.Model):
    product = models.ForeignKey(
        Product,
    )
    order_quantity = models.IntegerField(
        default = 0
    )
    order_date = models.DateField(
        default = datetime.datetime.now()
    )
    received = models.BooleanField(
        default = False
    )
    order_file = models.FileField(
        upload_to = 'reorder_documents/',
        null = True,
        blank = True
    )
    def __unicode__(self):
        return u'%s' % (self.product)

    def save(self, *args, **kwargs):
        # create the text file 
        filename =  str(self.product)+'_'+str(self.order_date)+".csv"
        path = os.path.join(MEDIA_ROOT, 'reorder_documents', filename)
        print path
        f = open(path, 'wrb')
        f.truncate()
        writer = csv.writer(f)
        writer.writerow((self.product, self.order_quantity))
        f.close()
        self.order_file = ContentFile(f)

        #save everything
        super(ReOrder, self).save(*args, **kwargs)  # Call the "real" save() method.

这会将文件创建并保存在我想要的位置,但不会将其保存到模型中。我该怎么做?

1 个答案:

答案 0 :(得分:0)

Django的FileField只在DB中存储字符串,因此您只能保存文件路径:

def save(self, *args, **kwargs):
    # create the text file 
    filename =  str(self.product)+'_'+str(self.order_date)+".csv"
    path = os.path.join(MEDIA_ROOT, 'reorder_documents', filename)
    print path
    f = open(path, 'wrb')
    f.truncate()
    writer = csv.writer(f)
    writer.writerow((self.product, self.order_quantity))
    f.close()
    self.order_file = os.path.join('reorder_documents', filename)
    super(ReOrder, self).save(*args, **kwargs)