【问题标题】:How can I lists all the products according to their foreign key?如何根据外键列出所有产品?
【发布时间】:2021-02-18 10:57:12
【问题描述】:

我正在使用 django 框架开发我的第一个 eshop 网站,但遇到了一个问题。 我为不同种类的产品(如笔记本电脑、书籍等)创建了一个通用模型。添加到网站的每个产品都可以通过将产品链接到特定类别的外键找到。

问题是我如何才能在laptops.html 上只显示具有指向正确类别的外键的产品?例如,仅显示笔记本电脑类别的产品。 非常感谢您的宝贵时间!

编辑: 在网址中:

urlpatterns=[
    path('', views.HomePage.as_view(), name='home'),
    path('ComputerScience/', views.ComputerScience.as_view(), name='computer_science'),
    path('category/<int:category_pk>/list-products/', views.CompSProd.as_view(), name='category_products_list')]

在computerscience.html 中,我呈现所有类别。 在 views.py 中,我有两个控制器,例如,第一个用于类别,第二个用于笔记本电脑。

views.py

class ComputerScience(ListView):
    model = ComputerScienceCategory
    template_name = "computer_science.html"
    context_object_name = "category"

class CompSProd(ListView):
    model = ComputerScienceProducts
    template_name = "laptops.html"
    context_object_name = "products"

    def get_queryset(self):
        queryset = super().get_queryset()
        # If you wish to still keep the view only for specific category use below line
        category = get_object_or_404(ComputerScienceCategory, pk=self.kwargs.get('category_pk'))
        queryset = queryset.filter(category=category)
        return queryset

这里有我想要显示所有类别的模板。

computer_science.html

<div class="computerScienceContent" id="slide">
    {% for cat in category %}
        <a href="{% url 'category_products_list' category.pk %} " id="aBar">
                <div>
                    <h4 class="cSh">{{ cat.name }}</h4>
                    <img src="{{ cat.img.url }}" alt="image" class="img">
                </div>
            </a>
    {% endfor %}

这是笔记本电脑的 html,我想在其中显示整个产品。

laptops.html
{% extends 'index.html' %}
{% block title %}
    <title>Laptops</title>
{% endblock %}
{% block cont2 %}
  
{% endblock %}

我的主要目标是拥有一个页面(computerscience.html),其中我显示了一个包含所有可用类别的列表,当您单击一个类别时,将您重定向到另一个页面,其中列出了所有属于的产品到那个类别。

这是向我抛出的错误:

Reverse for 'category_products_list' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category_pk>[0-9]+)/list\\-products/$']

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    您应该覆盖get_queryset 来过滤您的对象。此外,当您为特定类别实例编写视图时,您最终会编写很多视图,而且当添加新类别时,这将非常乏味,您应该为所有类别使用一个视图。试试这个:

    from django.shortcuts import get_object_or_404
    
    class CompSProd(ListView):
        model = ComputerScienceProducts
        template_name = "laptops.html"
        context_object_name = "products"
        
        def get_queryset(self):
            queryset = super().get_queryset()
            category = get_object_or_404(ComputerScienceCategory, pk=self.kwargs.get('category_pk')) # Assuming category_pk will be passed in url
            # If you wish to still keep the view only for specific category use below line
            # category = get_object_or_404(ComputerScienceCategory, pk=<pk-of-category-here>)
            queryset = queryset.filter(category=category)
            return queryset
    

    要在 url 中传递类别主键,您需要执行以下操作:
    在你的 urls.py 中:

    urlpatterns = [
        ...
        path('category/<int:category_pk>/list-products/', views.CompSProd.as_view(), name='category_products_list'),
        ...
    ]
    

    现在在显示所有类别的页面中:

    {% for cat in category %}
        <a href="{% url 'category_products_list' cat.pk %}" id="aBar">
            <div>
                <h4 class="cSh">{{ cat.name }}</h4>
                <img src="{{ cat.img.url }}" alt="image" class="img">
            </div>
        </a>
    {% endfor %}
    

    你也写了id="aBar",但这一行是循环的,这意味着你最终会得到多个相同的ID,你应该改用一个类。

    【讨论】:

    • 如何在laptops.html 的url 中传递类别pk ?我的意思是,它不会从数据库中获取当前笔记本电脑的 pk 吗?确实,这种方式更加熟练,因为我不必为 4 个不同的类别创建 4 个不同的视图。
    • @tudor.il 我已经编辑了我的答案,请检查。
    • 我试过你的代码,但它给我抛出了这个错误:Reverse for 'category_products_list' with arguments '('',)' not found。尝试了 1 种模式:['laptop/(?P[0-9]+)/$'。我试图遵循您的逻辑,但我想我在某个地方弄错了,我无法弄清楚。 :(
    • @tudor.il 空字符串可能意味着您正在使用不存在的变量,例如{% url 'category_products_list' this_variable_does_not_exist %}。您有类别的列表视图吗?在它里面应该做这样的事情:{% for cat in category %} 然后在那个循环里面&lt;a href="{% url 'category_products_list' cat.pk %}"&gt;{{ cat.name }}&lt;/a&gt;。 (顺便说一句,你应该使用categories而不是category来表示复数)
    • 确实,我有一个模板可以渲染整个类别。在那里,放置了迭代器。在 urls 中,我复制粘贴了您的 url 并在 views.py 中,因为我编写了第一段代码。它仍然不起作用。在 category.html (我渲染分类的模板,我将 context_object_name 命名为类别。我有存储在数据库中的项目,我错过了一些东西,我无法弄清楚..但是非常感谢你的帮助。我会尝试更难!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多