如何正确保存或更新模型中列表的值?

时间:2019-06-05 21:49:30

标签: python django django-queryset

我有以下型号:

class Tarifa_Sem (models.Model):
    limit_inferior_isr = models.DecimalField (max_digits = 10, decimal_places = 2)
    limit_superior = models.DecimalField (max_digits = 10, decimal_places = 2)
    cuota_fija_t = models.DecimalField (max_digits = 10, decimal_places = 2, blank = True)
    percentage_over_excess = models.DecimalField (max_digits = 10, decimal_places = 2)
 
class Calculator_isr (models.Model):
    rate = models.ForeignKey (Rate_Sem, on_delete = models.CASCADE, null = True, blank = True, related_name = 'calculators')
    base_gravada = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True)
    limite_inf_calculo = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True)
    percentage_excent_li = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True)
    fixed_ quota = models.DecimalField (max_digits = 10, decimal_places = 2, null = True, blank = True)

我通过迭代base_gravada字段的值来进行查询。

    results = [
        Tarifa_Sem.objects.filter (limite_superior__gte = obj.base_gravada)
        .values_list ('limite_inferior_isr', 'cuota_fija_t', 'percentage_over_excess')
        . First ()
        for obj in Calculadora_isr.objects.all ()
    ]

此查询返回以下列表:

[(Decimal ('133.22'), Decimal ('2.59'), Decimal ('6.40')),
(Decimal ('8790.96'), Decimal ('1649.34'), Decimal ('30 .00 ')), 
(Decimal ( '2765.43'), Decimal ('292.88'), Decimal ('21 .36 ')), 
(Decimal (' 8790.96 '), Decimal (' 1649.34 '), Decimal ('30 .00'))]

要保存,请使用create()方法:

 

for t in results:
    ... Calculadora_isr.objects.create (limite_inf_calculo = t [0],
     percentage_excent_li = t [2], fixed_ quota = t [1]). Save ()

在指示要保留的列表的字段和索引的地方,问题是它没有将它们保存在具有base_gravated初始值的ID内,如果不是的话,我创建了新值:

+------------------------------------------------------------------------------------+
|                            Model Calculadora_isr                                   |
+--------------------------------------+----------------------+----------------------+
|id |base_gravada| limite_inf_calculo  |       fixed_ quota   |  percentage_excent   |
+---+------------+---------------------+ ---------------------+ ---------------------+
|1  |  1000.00   |                     |                      |                      |
+---+------------+---------------------+ ---------------------+ ---------------------+
|2  | 10000.00   |                     |                      |                      |
+---+------------+---------------------+----------------------+ ---------------------+
|3  |  5000.00   |                     |                      |                      |
+---+------------+---------------------+ ---------------------+ ---------------------+
|4  | 10000.00   |                     |                      |                      |
+---+------------+---------------------+ ---------------------+ ---------------------+
|5  |            |        133.22       |         2.59         |          6.40        |
+---+------------+---------------------+ ---------------------+ ---------------------+
|6  |            |       8790.96       |      1649.34         |         30.00        |
+---+------------+---------------------+----------------------+ ---------------------+
|7  |            |       2765.43       |       292.88         |         21.36        |
+---+------------+---------------------+ ---------------------+ ---------------------+
|8  |            |       8790.96       |      1649.34         |         30.00        |
+---+------------+---------------------+ ---------------------+ ---------------------+

我需要的是能够将值保存在我的Calculadora_isr模型中,如下所示:

+------------------------------------------------------------------------------------+
|                            Model Calculadora_isr                                   |
+--------------------------------------+----------------------+----------------------+
|id |base_gravada| limite_inf_calculo  |       fixed_ quota   |  percentage_excent   |
+---+------------+---------------------+ ---------------------+ ---------------------+
|1  |  1000.00   |       133.22        |           2.59       |          6.40        |
+---+------------+---------------------+ ---------------------+ ---------------------+
|2  | 10000.00   |      8790.96        |        1649.34       |         30.00        |
+---+------------+---------------------+----------------------+ ---------------------+
|3  |  5000.00   |      2765.43        |         292.88       |         21.36        |
+---+------------+---------------------+ ---------------------+ ---------------------+
|4  | 10000.00   |      8790.96        |        1649.34       |         30.00        |
+---+------------+---------------------+ ---------------------+ ---------------------+

我需要帮助,谢谢您

2 个答案:

答案 0 :(得分:0)

在创建results列表期间,还要添加实例的pk,以后再使用它来更新实例。

results = [
    [obj.id, Tarifa_Sem.objects.filter(limite_superior__gte = obj.base_gravada)
    .values_list('limite_inferior_isr', 'cuota_fija_t', 'percentage_sobre_excedente')] for obj in Calculadora_isr.objects.all ()
]

for t in results:
    instance = Calculadora_isr.objects.get(t[0])
    instance.limite_inf_calculo = t[1][0][0]
    instance.percentage_excendente_li = t[1][0][2]
    instance.cuota_fija = t[1][0][1]
    instance.save()

答案 1 :(得分:0)

您的问题对我来说有点不清楚,,但是尝试这样的事情。

# create list of dicts, to make association between PK's and values (Which represents QuerySet)
results = [
    {obj.pk: Tarifa_Sem.objects.filter (limite_superior__gte=obj.base_gravada).values_list ('limite_inferior_isr', 'cuota_fija_t', 'percentage_sobre_excedente').first()}
    for obj in Calculadora_isr.objects.all ()
]
# iterate over results and find row based on dict key, and update associated row based on dict value
for result in results:
    for k, v in result.items():    
        try:
            get_instance = Calculadora_isr.objects.get(pk=k)   #limite_inf_calculo =t[0],percentage_excendente_li=t[2], cuota_fija=t[1])
            # if model found
            get_instance.limite_inf_calculo = v[0]
            get_instance.percentage_excent_li = v[2]
            get_instance.fixed_quota = v[1]
            get_instance.save()
        except Calculadora_isr.DoesNotExist:
            pass 

此外,first()表示QuerySet集合中的第一个,而不是数据库中的第一个(基于行ID)。最好使用earliest('pk')代替first()(IMHO)。两者都是QuerySet方法。

希望,对您有帮助。