【问题标题】:django validate values for calculationdjango 验证计算值
【发布时间】:2022-01-09 20:22:10
【问题描述】:

嘿嘿!

我需要在我的 django 视图中对过滤后的数据进行一些简单的计算。当在所选过滤器中有值时,这工作得很好。如果该值为 0 或 None 我收到服务器错误并且站点崩溃。因此我需要一个验证器来确保给定的值不是 0 也不是 None。

(我的尝试在底部)目前,如果添加了验证器,它会给我“浮动”对象不可调用的消息,即使在进入过滤器选项/模板之前也是如此。

并且:在我的模型中,我从中获取值的模型是 m2m。对于每个值,可以选择一个单位,我只想计算单位是否相同,否则我想得到一个警告。

有谁知道如何做到这一点?或者去哪里看?

感谢任何帮助! :)

# validators.py

def validate_values(value):
    if value == 0:
        raise ValidationError(_('One of the given values is 0 or empty and the calculation therefore cannot be proceeded.'),
                              code='notinrange')
# views.py

def process_mass_intensity(request):
    plants = Plant.objects.all()

    myFilter = PlantsNameFilter(request.GET, queryset=plants)
    plants = myFilter.qs

    total_m = plants.aggregate(Sum('used_in_plant__value'))['used_in_plant__value__sum']

    product_m = plants.aggregate(product_mass=Sum('used_in_plant__value',
                                                  filter=Q(used_in_plant__input_or_output='OUT')))['product_mass'](validators=[validate_values])

    pmi = (total_m / product_m)(validators=[validate_values])

    context = {"plants": plants, "myFilter": myFilter, "total_m": total_m, "product_m": product_m, "pmi": pmi}
    return render(request, 'kpi/process_mass_intensity.html', context)
# models.py

class Plant(models.Model):
    name = models.CharField(
        max_length=200
    )
    used_xducts = models.ManyToManyField(
        Xduct,
        through="UsedXduct",
        blank=True,
        related_name="used_in_plant"
    )



class UsedXduct(models.Model):
    plant = models.ForeignKey(
        Plant,
        on_delete=models.PROTECT,
        related_name="used_in_plant"
    )
    xduct = models.ForeignKey(
        Xduct,
        on_delete=models.PROTECT,
        related_name="xduct"
    )
    value = models.FloatField()
    quantity = models.ForeignKey(
        Quantity,
        on_delete=models.PROTECT
    )
    unit = models.ForeignKey(
        Unit,
        on_delete=models.PROTECT
    )

【问题讨论】:

    标签: django django-models django-views calculation django-validation


    【解决方案1】:

    验证器应用于字段级别。您也可以在此处使用 MinValueValidator 代替自定义验证器函数。让我们分解一下。

    您可能会收到此错误的原因是因为您将一个值(具体来说是一个浮点数)乘以 (validators=[validate_values]),这是一个函数。这真的没有意义。

    相反,您可能希望将验证器放在模型的字段声明中。所以:

    from django.core.validators import MinValueValidator
    
    class UsedXduct(models.Model):
        plant = models.ForeignKey(
            Plant,
            on_delete=models.PROTECT,
            related_name="used_in_plant"
        )
        xduct = models.ForeignKey(
            Xduct,
            on_delete=models.PROTECT,
            related_name="xduct",
            validators=[MinValueValidator(0)]
        )
        value = models.FloatField()
        quantity = models.ForeignKey(
            Quantity,
            on_delete=models.PROTECT,
            validators=[MinValueValidator(0)]
        )
        unit = models.ForeignKey(
            Unit,
            on_delete=models.PROTECT
        )
    

    或者,要在创建模型时不执行验证器,您可以简单地在视图本身中运行验证器函数:

    def process_mass_intensity(request):
        plants = Plant.objects.all()
    
        myFilter = PlantsNameFilter(request.GET, queryset=plants)
        plants = myFilter.qs
    
        total_m = plants.aggregate(Sum('used_in_plant__value'))['used_in_plant__value__sum']
    
        product_m = validate_values(plants.aggregate(product_mass=Sum('used_in_plant__value', filter=Q(used_in_plant__input_or_output='OUT')))['product_mass'])
    
        pmi = validate_values(total_m / product_m)
    
        context = {"plants": plants, "myFilter": myFilter, "total_m": total_m, "product_m": product_m, "pmi": pmi}
        return render(request, 'kpi/process_mass_intensity.html', context)
    

    希望这会有所帮助,如果您有任何问题,请告诉我。

    【讨论】:

    • 遗憾的是这对我不起作用。我仍然收到不支持 NoneType 的错误。 (模型之外)也许验证器尝试在这里对我不起作用。您是否还有其他想法,我该如何实现,我会收到一条警告消息,由于缺少值或不匹配的单位而不是服务器错误而无法进行计算?
    猜你喜欢
    • 2011-05-28
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2013-01-12
    • 2012-12-17
    • 2011-06-12
    • 2021-06-08
    • 2017-03-28
    相关资源
    最近更新 更多