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

Viewed 201

I have the following class in 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()
    .....

Now in my view I have created the following variable:

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

I want to fill this variable with the product of quant*price for each month (e.g. in monthly_income[0] = quant_jan*price_jan and so on). How could get it with python?

1 Answers

You need to normalize the database a bit better. What I would do is something more like this:

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]
    ...
    

Alternatively, there is a way to do the multiplication right in the query and make the result a flat values list, but it is a bit more complex. Above is what is easiest.

To create an entry for each month, you simply do this in views.py which catches data from a template with a form in it:

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>

Or just use the Django admin to create a new database row (object) manually for each month you need data for. Wasn't sure how you are getting the data for your model input into the system.

Related