如何从查询集值访问django模板语言的外键

wz3gfoph  于 2023-05-19  发布在  Go
关注(0)|答案(1)|浏览(106)

这是我的模型

class MainCategory(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self) :
        return self.name
    
class Category(models.Model):
    main_category = models.ForeignKey(MainCategory, on_delete=models.CASCADE, related_name="maincategory")
    name = models.CharField(max_length=100)

    def __str__(self) :
        return self.name + "--" + self.main_category.name
    
class SubCategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name")
    name = models.CharField(max_length=100)

    def __str__(self) :
        return self.name

检视方式

def Home(request):
    sliders = Slider.objects.all()
    banners = BannerArea.objects.all()
    main_category = MainCategory.objects.all()
    context = {
        'sliders' : sliders,
        'banners' : banners,
        'main_category' : main_category
    }
    return render(request, 'main/home.html', context)

我想显示主类别和子类别和类别。显示主类别,但不显示子类别和类别。你能帮我解决这个问题吗
Header.html文件

<div class="cat__menu">
                                <nav id="mobile-menu" style="display: block;">
                                    <ul>

                                        {% for i in main_category %}

                                        <li>
                                            <a href="shop.html"> {{ i.name }} <i class="far fa-angle-down"></i></a>
                                            <ul class="mega-menu">

                                                {% for cat in i.category_set.all %}

                                                <li><a href="shop.html">{{cat.name}}</a>
                                                    <ul class="mega-item">
                                                        {% for sub_cat in cat.subcategory_set.all %}
                                                        <li><a href="product-details.html">{{sub_cat.name}}</a></li>
                                                        {% endfor %}
                                                        
                                                    </ul>
                                                </li>
                                                {% endfor %}
  
                                            </ul>
                                        </li>

                                        {% endfor %}
                                        
                                    </ul>
                                </nav>
                            </div>

我想显示主类别和子类别和类别。显示主类别,但不显示子类别和类别。你能帮我解决这个问题吗

fxnxkyjh

fxnxkyjh1#

它不起作用,因为您已经为反向关系定义了相关名称。因此,您应该使用相关名称而不是<modelname>_set,如下所示:

{% for i in main_category %}
    {% for cat in i.maincategory.all %}
         {{ cat }}
        {% for sub_cat in cat.subcategory_set.all %}
         {{ sub }}
        {% endfor %}
    {% endfor %}
  {% endfor %}

相关问题