2016-03-04 90 views
2

我有这个在我的模型:如何在查询集对象中插入新字段?

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 

我想每个产品我dollar_price的观点:

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}) 

在这里我把注释行了,我知道我可以这样做,但我想创建一个新的“p”对象的字段,并填充它“dollar_price”。

我该怎么做类似的事情?

+0

但是,这个说法?我可以在模板中做'p.dollar_price(10)'或类似的东西吗? – hectorlr22

+0

是的,我没有注意到第一个参数 – Sayse

回答

1

productProduct一个实例,你应该新字段分配给它

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

这个循环后,您将有实例的查询集pnew_field

+0

非常感谢,你是对的!这解决了我的“问题” – hectorlr22

相关问题