我正在尝试使用迁移选项将一些测试数据上传到应用程序。所有数据都存储在应用程序中的.Yaml文件中,还有一些其他迁移程序可以完美地上传所有数据。< / p>
但是这个有问题。在此模型(事务)中,我创建了3个自写字段,这些字段是在调用save()方法时计算的。当我通过View发送数据时,此过程运行完美。但是,当我通过迁移发送它时,失败了,好像保存方法没有被覆盖。我不知道该怎么做才能完成迁移。
迁移
from django.db import migrations
from django.core import serializers
def transactions(apps, schema_editor):
with open('fixtures/transactions.yaml') as trans:
for obj in serializers.deserialize("yaml", trans):
t=apps.get_model("acounts", "Transactions")()
cat=apps.get_model("acounts","Category")
.objects.get(pk=obj.object.category.pk)
cuen=apps.get_model("acounts", "Acount").objects.get(pk=obj.object.acount.pk)
print(obj)
t.tipo=obj.object.tipo
t.description=obj.object.description
t.monto=obj.object.monto
t.date=obj.object.date
# t.category=obj.object.category
t.category=cat
# t.acount=obj.object.acount
t.acount=cuen
t.save()
class Migration(migrations.Migration):
dependencies = [
('acounts', '0002_populate_acounts'),
]
operations = [
(migrations.RunPython(transactions))
]
模型
class Transactions(models.Model):
TYPE_CHOICES = (
('GASTO', 'Gasto'),
('INGRESO', 'Ingreso'),
)
tipo = models.CharField(
choices=TYPE_CHOICES,
max_length=20
)
description=models.CharField(max_length=100)
monto=models.DecimalField(max_digits=25,
decimal_places=2,
null=False)
category=models.ForeignKey('Category',
on_delete=models.CASCADE,
null=False)
acount=models.ForeignKey('Acount',
on_delete=models.CASCADE,
null=False)
date=models.DateField()
total_USD=models.DecimalField(
max_digits=25,
decimal_places=2,
editable=False);
total_BTC=models.DecimalField(
max_digits=25,
decimal_places=9,
editable=False);
total_BSS=models.DecimalField(
max_digits=25,
decimal_places=2,
editable=False);
total_EUR=models.DecimalField(
max_digits=25,
decimal_places=2,
editable=False);
created_at=models.DateTimeField(
auto_now_add=True,
editable=False)
updated_at=models.DateTimeField(
auto_now=True,
editable=False)
def save(self):
cotizations=Currency.objects.all()
currency=self.acount.currency.name
in_usd=self.monto/Currency.objects.get(name=currency).price_USD_now
query_btc=in_usd*Currency.objects.get(name='BTC').price_USD_now
query_bss=in_usd*Currency.objects.get(name='YEN').price_USD_now
query_eur=in_usd*Currency.objects.get(name='EUR').price_USD_now
self.total_USD=in_usd
self.total_BTC=query_btc
self.total_YEN=query_bss
self.total_EUR=query_eur
super(Transactions, self).save()
return query_btc;
错误
raise utils.IntegrityError(*tuple(e.args))
django.db.utils.IntegrityError: (1048, "Column 'total_USD' cannot be null
通过视图完成时,同一方法运行完美,如何使用覆盖的.save()方法为此模型创建数据迁移?