hectorlr22
hectorlr22

Reputation: 123

How to insert a new field in a queryset object?

I have this in my models:

class Product(models.Model):
    name = models.CharField(max_length=50)
    category = models.ForeignKey(Categoria)
    price = models.DecimalField()

    def __str__(self):
        return self.name

    def dollar_price(self, dollar_price):
        return self.price * dollar_price

And I want to get my dollar_price per Product in the views:

def products(request):
    p = Product.objects.all()
    dollar = 10
    for product in p:
        dollar_price = product.dollar_price(dollar)
        p[product].new_field = dollar_price # This line is the problem
    return render(request, "main/products.html", {"p":p})

On the line where I put the comment, I know that I can't do that, but I want to create a new field of that "p" object and fill it with that "dollar_price".

How can I do something similar?

Upvotes: 4

Views: 5193

Answers (1)

Yablochkin
Yablochkin

Reputation: 136

product is an instance of Product and you should assign new field to it

for product in p:
    dollar_price = product.dollar_price(dollar)
    product.new_field = dollar_price # This line is the problem

After this loop you will have queryset p of instances with new_field

Upvotes: 6

Related Questions