0
我正在编写一个项目,目标是使用Django构建一个类似管理(业务管理,如何说)的东西。其实,我需要一个全局变量的支持,因为产品是通过增加代码来识别的,有时候我重置(它不是主键,只是我用来工作的代码)。 因此,为了避免使用全局变量,也是由于如果服务器重新引导会导致问题,我想写一个文本文件的实际代码。读写文本文件
使用保存方法覆盖我保留写在这个文件中的数字,我用它来填补产品代码字段。然后我增加写在文件中的数字并关闭它。这样,我只需要在文件中用文本编辑器编写“0”(零)来重置che代码!如果服务器重新启动,我不喜欢失去使用其他方法的实际数量(即:变量保存在高速缓存)
我遇到的错误是:没有这样的文件/目录名为product_code.txt
这里模型的代码:
class Product(models.Model):
code = models.AutoField(primary_key=True, editable=False)
#category = models.ForeignKey(Category)
product_code = models.IntegerField(editable=False, blank=True, null=True, verbose_name="codice prodotto")
description = models.CharField(max_length=255, verbose_name="descrizione")
agreed_price = models.DecimalField(max_digits=5, decimal_places=2, verbose_name="prezzo accordato")
keeping_date = models.DateField(default=datetime.date.today(), verbose_name="data ritiro")
selling_date = models.DateField(blank=True, null=True, verbose_name="data di vendita")
discount = models.SmallIntegerField(max_length=2, default=0, verbose_name="sconto percentuale applicato")
selling_price = models.DecimalField(
max_digits=5, decimal_places=2, blank=True, null=True, verbose_name="prezzo finale"
)
sold = models.BooleanField(default=False, verbose_name="venduto")
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
if self.product_code is None:
handle = open('product_code.txt', 'r+')
actual_code = handle.read()
self.product_code = int(actual_code)
actual_code = int(actual_code) + 1 # Casting to integer to perform addition
handle.write(str(actual_code)) # Casting to string to allow file writing
handle.close()
if self.sold is True:
if self.selling_date is None or "":
self.selling_date = datetime.date.today()
if self.selling_price is None:
self.selling_price = self.agreed_price - (self.agreed_price/100*self.discount)
super(Product, self).save()
class Meta:
app_label = 'business_manager'
verbose_name = "prodotto"
verbose_name_plural = "prodotti"
文件product_code.txt
坐落在models.py
同一个目录我保证误差指的是代码行
handle = open('product_code.txt', 'r+')
因为我用调试器检查过它。
任何想法来解决这个问题?谢谢
您应该将文件存储在您的django根目录(您运行django的目录)中,或者您可以在代码中使用绝对路径。无论如何,我建议将product_code存储在数据库中而不是文件系统(f.e.表全局变量,包含2个字段:variable_name和value。 – Jiri 2014-09-22 14:48:37