如何在Django模型中添加计算字段

3zwtqj6y  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(126)

我正在建立一个数据库系统,并试图添加到模型计算字段以及模板。我想将字段自动生成的结果转换为在两个字段上输入的值。

This is my model.py:

class VinanPet(models.Model):
    transaction_Date = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True, null=True)
    entry_Date = models.DateTimeField(null=True)
    branch = models.CharField(max_length=300, null=True)
    product = models.CharField(max_length=300, null=True)
    tank_Opening = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    tank_Closing = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    tank_Difference = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    pump_Opening = models.FloatField(null=True)
    pump_Closing = models.FloatField(null=True)
    pump_Difference = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    price = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    amount = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    expenses = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    bank = models.DecimalField(max_digits=13, decimal_places=3, null=True)
    teller_id = models.IntegerField(null=True)
    teller = models.ImageField(upload_to="teller", null=True)

字符串
这是我的forms.py

from django import forms
import calculation
from django.forms.widgets import NumberInput
from .models import VinanPet

class ManagerForm(forms.ModelForm):
    
    class Meta:
        model = VinanPet
        fields = "__all__"
        widget = {
            'entry_Date': forms.DateInput(attrs={'type': 'date'}),
            'tank_Difference': forms.DecimalField(disabled=True,widget=calculation.FormulaInput('tank_Opening-tank_Closing'))
        }


计算字段仅在表单上有效,不在数据库上。

jchrr9hc

jchrr9hc1#

我不认为这是作为一个功能添加到Django中的。您可以覆盖save()方法或使用Django pre_save()信号。

xpcnnkqh

xpcnnkqh2#

您可以查看Django ComputedFields库:https://django-computedfields.readthedocs.io/en/latest/manual.html#basic-usage

from django.db import models
from computedfields.models import ComputedFieldsModel, computed, compute

class Person(ComputedFieldsModel):
    forename = models.CharField(max_length=32)
    surname = models.CharField(max_length=32)

    @computed(models.CharField(max_length=32), depends=[('self', ['surname', 'forename'])])
    def combined(self):
        return f'{self.surname}, {self.forename}'

字符串
第二件要考虑的事情是只使用propertyhttps://www.geeksforgeeks.org/python-property-decorator-property/
在这种情况下,它不会存储在DB中,而是在需要时动态计算

相关问题