Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 297
hectorlr22 Avatar asked Oct 19 '25 13:10

hectorlr22


1 Answers

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

like image 185
Yablochkin Avatar answered Oct 22 '25 06:10

Yablochkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!