简体   繁体   English

在Django模板中访问临时模型数据?

[英]Accessing temporary model data in a django template?

I have the following view code which adds some temporary data to a Django model instance contained within a ManyToMany relationship. 我有以下视图代码,该代码将一些临时数据添加到ManyToMany关系中包含的Django模型实例中。 I'd like to be able to access that data within the template but I'm not sure how. 我希望能够访问模板中的数据,但不确定如何。

@login_required()
def shopping_cart(request):
    try:
        cart = ShoppingCart.objects.get(user__exact=request.user)
    except ShoppingCart.DoesNotExist:
        cart = ShoppingCart(user=request.user)
        cart.save()

    for album in cart.albums.all():
        album.vat_rate = request.session['vat_rate']
        album.total_cost = (((album.price / 100) * album.vat_rate) + album.price)

    return render_to_response('sym_money/shopping_cart.html',
                          {'shopping_cart': cart},
                          context_instance=RequestContext(request))

I need to be able to access the vat_rate and the total_cost in the template by doing: 我需要通过执行以下操作来访问模板中的vat_rate和total_cost:

{% for album in cart.albums.all %}
    {{ album.vat_rate }}
    {{ album.total_cost }}
{% endfor %}

None of the temporary data has any fields in the model and I don't want to save it to the database either, I just want to be able to access the temporary data in the model from the templates. 没有临时数据在模型中有任何字段,我也不想将其保存到数据库中,我只想能够从模板访问模型中的临时数据。

In the template, when you do {% for album in cart.albums.all %} , you're creating a completely new queryset so your previous annotated objects are all discarded. 在模板中,当您{% for album in cart.albums.all %} ,您将创建一个全新的查询集,因此所有先前注释的对象都将被丢弃。

Save the album queryset as a variable in your view, iterate it and anotate the objects like you're doing, then pass this variable to the context. 将相册查询集另存为视图中的变量,对其进行迭代并注释对象,就像您正在做的那样,然后将此变量传递给上下文。

Hint: render_to_response is oldskool - just use render . 提示: render_to_response是oldskool-只需使用render

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM