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

标签 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

我想在 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”填充它。

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

最佳答案

productProduct 的一个实例你应该为它分配新的字段

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/

相关文章:

python-2.7 - Python多处理: how to exit cleanly after an error?

python - 导入 pandas 模块给出属性错误

python - 如何为 Windows 64 位 Python 2.7 编译孔雀鱼?

MySQL 自连接查询优化

Django Crispy Forms 重新排列布局并保留 Bootstrap 内联格式?

python - csv 文件土耳其语字符未显示

python - 转换时间(HH :MM:SS) to minutes in python

python - 单击按钮更改图像

python - django MultiValueDictKeyError 错误,我该如何处理

python - 使用 Django 进行站点范围的缓存 - 注销时密码保护页面的问题