根据匹配日期从其他模型中获取价值

时间:2015-11-11 15:42:43

标签: python django filter model

基本上,我有2个模型,模型1是过去5年每天的汇率列表。模型2是发票模型。

我想要发生的事情是,保存发票模型时,它与发票日期相匹配,与特定日期在汇率表中相匹配,并将相应的汇率导入发票模型上的特定字段。

我一直试图在保存覆盖中使用这样的东西:

   invdate = obj.invoiceDate
    obj.exchange_relation=xchangeRates.objects.filter(date=invdate).values('id')
    obj.euroRate= exchangeRates.objects.filter(date=invdate).values('EuroRate')     

非常感谢提前! (对不起,没有更多的代码,我想我已经把这个混淆了,并删除了很多我尝试过的东西!

根据要求提供的模型:

class exchangeRates(models.Model):
date = models.DateField(verbose_name='Exchange Rate Date')
EuroRate = models.DecimalField(verbose_name="Euro Rate", max_digits=5, decimal_places=4)
DollarRate = models.DecimalField(verbose_name="Dollar Rate", max_digits=5, decimal_places=4)

class Invoice(models.Model):
fullname = models.CharField(null=True, blank=True, max_length=250, verbose_name='Invoice Name')
ctr = models.ForeignKey(CTR, related_name='CTR', verbose_name='CTR')
invoiceNo = models.CharField(max_length=6)
invoiceDate = models.DateField(null=True, verbose_name='Invoice Date')
invoiceStatus = models.ForeignKey(InvStatus, verbose_name='Status')
currency = models.CharField(null=False, max_length=3, verbose_name='Currency')
exchangeRate = models.FloatField(verbose_name='exchange rate', default=0.0)
cathieValue = models.FloatField(verbose_name='Cathie Value', default=0.0)
subcontractorValue = models.FloatField(verbose_name='Subcontractor Value', default=0.0)
expensesValue = models.FloatField(verbose_name='Expenses', default=0.0)
deductionValue = models.FloatField(verbose_name='Deduction', default=0.0)
vatInc = models.BooleanField(verbose_name='VAT Included')
netValue = models.FloatField(verbose_name='Net', default=0.0)
vatValue = models.FloatField(verbose_name='VAT', default=0.0)
GrossValue = models.FloatField(verbose_name='Gross', default=0.0)
euroRate = models.DecimalField(verbose_name='Euro Rate', max_digits=5, decimal_places=4)
dollarRate = models.DecimalField(verbose_name='DollarRate', max_digits=5, decimal_places=4)

1 个答案:

答案 0 :(得分:1)

答案基于您在问题评论部分中的解释:

在保存覆盖中,请执行以下操作:

try:
    exrate = exchangeRates.objects.get(date=obj.invoiceDate)
    xeuroRate = exrate.euroRate
    xdollarRate = exrate.dollarRate 
except:
    xeuroRate = 0.0 # set default value
    xdollarRate = 0.0 # set default value

obj.euroRate = xeuroRate
obj.dollarRate = xdollarRate
obj.save()