我的模型中有这个:
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
我想在 View 中获取每个产品的美元价格:
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”填充它。
我怎样才能做类似的事情?
最佳答案
product
是 Product
的一个实例你应该为它分配新的字段
for product in p:
dollar_price = product.dollar_price(dollar)
product.new_field = dollar_price # This line is the problem
在此循环之后,您将拥有查询集
p
具有 new_field
的实例
关于django - 如何在查询集对象中插入新字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791092/