【问题标题】:How to get the product of two fields in my Django Model如何在我的 Django 模型中获取两个字段的乘积
【发布时间】:2020-10-15 23:54:38
【问题描述】:

我在 django 中有以下课程:

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怎么弄?

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-01-06
      • 1970-01-01
      • 1970-01-01
      • 2015-05-31
      • 1970-01-01
      • 2021-11-05
      • 2011-04-08
      • 2017-05-20
      • 2013-05-23
      相关资源
      最近更新 更多