您需要更好地规范化数据库。我会做的更像是这样的:
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 管理员为您需要数据的每个月手动创建一个新的数据库行(对象)。不确定如何将模型输入数据获取到系统中。