繁体   English   中英

如何在我的 Django Model 中获得两个字段的乘积

[英]How to get the product of two fields in my Django Model

我在 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_income[0] = quant_jan*price_jan等等)。 python 怎么能得到它?

您需要更好地规范化数据库。 我会做的是更像这样的事情:

模型.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)

视图.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 中执行此操作,它会从包含表单的模板中捕获数据:

视图.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()
     ...

模板.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 管理员为您需要数据的每个月手动创建一个新的数据库行(对象)。 不确定如何将 model 输入数据获取到系统中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM