我正在寻找一种动态添加额外属性到 Django 模型实例的方法,以便它们可以在模板中访问
例如,
在模型中
class Foo(models.Model):
name = models.TextField()
在 views.py 中
def my_view(request):
f = Foo.objects.get(id=1234)
# method in question
f.____add_extra_attribute____('extra_attribute', attr_value)
return render(request, 'my_template.html', {'foo_instance':f})
在 my_template.html 中
<h1>{{ foo_instance.name }}</h1>
<p>{{ foo_instance.extra_attribute }}</p>
有没有一种方法可以在不将实例呈现为字典而不是 Foo 模型对象的情况下完成此操作?
请您参考如下方法:
按照@mgilson 的评论,您可以将extra_attribute 传递给单独的上下文变量 中的模板:
def my_view(request):
f = Foo.objects.get(id=1234)
extra_attribute = attr_value
return render(request, 'my_template.html',
{'foo_instance': f, 'extra_attribute': attr_value})
如果你还想在模型实例上设置属性,你可以直接设置它:
f.extra_attribute = attr_value
