访问Django模板中由对象键入的字典

2024-04-26 23:15:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试访问django模板中的dict值。dict键是对象。以下是我的代码库片段:

型号.py

class ProductCategory(models.Mode):
    name = models.CharField(max_length=64, blank=False, null=False, unique=True)
    slug = models.SlugField(blank=False, null=False, unique=True)

class Product(models.Model):
    category = models.ForeignKey(ProductCategory, on_delete = models.CASCADE)

    # other fields
    pass

    def __str__(self):
        return self.title

views.py

def index(request):
    products = Product.objects.all()
    categorized_products = {}

    for p in products:
        prod_category = p.category
        temp = categorized_products.get(prod_category,[])
        temp.append(p)
        categorized_products[prod_category] = temp

    context = {'products_dict': categorized_products, 'categories': categorized_products.keys() }

    return render(request,'product/index.html', context=context)

mytemplate.html(相关代码片段)

            <div class="tab-content">
                {% for category in categories %}
                {% if not forloop.counter0 %}
                <div class="tab-pane fade in active" id="{{ category.slug }}">  
                {% else %}                  
                <div class="tab-pane fade in" id="{{ category.slug }}">
                {% endif %}
                    <div >
                        <h4>{{ category.description }}</h4>
                        <div class="container-fluid"> 
                            <div class="row">                                                                  
                                <div class="col-md-3"  style="border:1px solid red;">
                                {% for product in products_dict.category %}
                                    {{ product }}
                                {% endfor %}

当我使用调试器逐步检查代码时,我可以看到变量products_dict是一个dict,并且由视图正确填充。但是,当我运行代码时,for loop代码不会执行

类似地,当我在shell中运行views.py中的相同代码时,dict被正确填充,因此我知道数据库中有数据,并且检索到的数据被正确地传递到django模板

那么,为什么我无法访问模板中的dict值,为什么产品没有显示在我的模板中


Tags: 代码inpydiv模板falseformodels
1条回答
网友
1楼 · 发布于 2024-04-26 23:15:18

简单的答案是Django模板不会这样做。模板变量中的点引用执行字典查找(除其他外),但不基于另一个变量名的值:

Note that “bar” in a template expression like {{ foo.bar }} will be interpreted as a literal string and not using the value of the variable “bar”, if one exists in the template context.

https://docs.djangoproject.com/en/3.0/ref/templates/language/#variables

一般来说,我会通过安排一些可直接存在于category值上的iterable来解决这个问题,而不是尝试将category对象用作dict键。这可能是一个反向FK管理器:

{% for product in category.products_set.all %}

或者我在视图中的内存中类别对象上设置的东西,如果我需要转换或过滤每个类别的产品:

categories = ProductCategory.objects.all()
for category in categories:
    category.products = [transform_product_somehow(product) for product in category.products_set.all()]

(可选地使用fetch_related预取类别产品,而不是对每个类别进行额外查询。)

相关问题 更多 >