如何在查询集对象中插入新字段?

hec*_*r22 3 django python-2.7

我的模型中有这个:

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
Run Code Online (Sandbox Code Playgroud)

我想在视图中获取每个产品的美元价格:

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})
Run Code Online (Sandbox Code Playgroud)

在我发表评论的那一行,我知道我不能这样做,但我想创建一个“p”对象的新字段并用“dollar_price”填充它。

我怎样才能做类似的事情?

小智 5

product是一个实例,Product您应该为其分配新字段

for product in p:
    dollar_price = product.dollar_price(dollar)
    product.new_field = dollar_price # This line is the problem
Run Code Online (Sandbox Code Playgroud)

在此循环之后,您将拥有p实例的查询集new_field