python - 如何获取 Django 模型中两个字段的乘积

标签 python python-3.x django django-models django-views

我在 django 中有以下类(class):

class Income(models.Model):
    product=models.ForeignKey()
    byproduct=models.ForeignKey()
    quant_jan=models.DecimalField()
    quant_feb=models.DecimalField()
    price_jan=models.DecimalField()
    price_feb=models.DecimalField()
    .....

现在,在我看来,我创建了以下变量:

monthly_income= list(0 for m in range(12))

我想用每个月的 quant*price 的乘积填充此变量(例如 monthly_venue[0] = quant_jan*price_jan 等)。 怎么用python得到它?

最佳答案

您需要更好地标准化数据库。我想做的事情更像是这样的:

models.py:

class MonthIncome(models.Model):

    class Months(models.IntegerChoices):
        JAN = 1
        FEB = 2
        MAR = 3
        APR = 4
         ...

    product= models.ForeignKey()
    month = models.IntegerField(choices=Months.choices)
    qty = models.DecimalField()
    price = models.DecimalField()
    created = models.DateTimeField(default=datetime.now)

views.py:

def my_view(request):
    month_incomes = MonthIncome.objects.all().order_by('-month')
    monthly_income = [m.qty * m.price for m in month_incomes]
    ...
    

或者,有一种方法可以在查询中直接进行乘法并使结果成为平面值列表,但它有点复杂。以上是最简单的。

要为每个月创建一个条目,您只需在views.py中执行此操作,它会从包含表单的模板中捕获数据:

views.py:

def create_month_income(request):
        ... # get data from POST or whatever
    if request.method == "POST":
        data = request.POST.dict()
        product = Product.objects.get(id=data.get('product'))
        new_month = MonthIncome.objects.create(product=product, qty=data.get('qty'), price=data.get('price'), month=data.get('month'))
        new_month.save()
     ...

template.html:

<form method="post" action="{% url 'create_month_income' %}">
    <p><select name="product">
    {% for product in products.all %}
      <option value="{{ product.id }}">{{ product.name }}</option>
    {% endfor %}
    </select></p>
    <p><input type="text" name="month" id="month" placeholder="Month (number)"></p>
    <p><input type="text" name="price" id="price" placeholder="Price"></p>
    <p><input type="text" name="qty" id="qty" placeholder="Quantity"></p>
    <p><button type="submit" value="Submit"></p>
</form>

或者只是使用 Django 管理工具为您需要数据的每个月手动创建一个新的数据库行(对象)。不确定您如何将模型数据输入到系统中。

关于python - 如何获取 Django 模型中两个字段的乘积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62576798/

相关文章:

python - 寻找比 for 循环更快的方法来使用 Pandas 搜索和附加 DataFrame

python - 如何在两个不同的 docker 容器中的两个 django 应用程序之间建立连接?

python - 将已见集用于有向图与无向图

python - 在 Django 的管理器中验证对象属性

python - 如何登录graphql页面(localhost :8000/graphql) with django

python - 如何将 .csv 文件中的列存储到列表中?

python - 检测 python 脚本是从 ipython shell 运行,还是从命令行运行

python - 如何检查 chr() 的输出是否未定义

Python 3.5 : subclasses of int don't call the __index__ method?

python - 附加到 Django 中的对象