首页 > 解决方案 > 对象没有属性“entry_set”错误

问题描述

我是 Python 新手,正在尝试完成 Python Crash Course,但遇到了一个我无法弄清楚的问题。这是我的错误:

'Pizza' 对象没有属性 'entry_set'

在我的模型中,我在 Toppings 中为 Pizza 定义了外键,它工作正常,但我显然不明白这个entry_set定义。

这是我的网址代码:

from django.urls import path
from . import views

app_name = 'pizzas'

urlpatterns = [
    # home path
    path('', views.index, name='index'),
    # show all pizza names
    path('names/', views.names, name='names'),
    # show all pizza toppings
    path('toppings/', views.toppings, name='toppings'),
    # show a pizza and it's toppings
    path('names/<int:name_id>/', views.pizza, name='pizza'),
]

这是我的视图代码(如您所见,我有entry_set):

def pizza(request, name_id):
    """Show a single pizza and all it's toppings"""
    name = Pizza.objects.get(id=name_id)
    toppings = name.entry_set.order_by('topping')
    context = {'name': name, 'toppings': toppings}
    return render(request, 'pizzas/pizza.html', context)

最后,我的 HTML 代码:

{% extends 'pizzas/base.html' %}
{% block content %}

  <p>{{ name }}</p>

  <p>Toppings:</p>

    <ul>
      {% for topping in toppings %}
        <li>
            <p>{{ topping|linebreaks }}</p>
        </li>
    </ul>

{% endblock content %}

这是models.py:

from django.db import models


class Pizza(models.Model):
    """Pizza names """
    name = models.CharField(max_length=50)

    def __str__(self):
        """Return a string representation of the model"""
        return self.name


class Toppings(models.Model):
    """Pizza toppings """
    pizza = models.ForeignKey(Pizza, on_delete=models.DO_NOTHING)
    topping = models.CharField(max_length=50)

    def __str__(self):
        """Return a string representation of the model"""
        return self.topping

先感谢您!

标签: pythondjangojinja2

解决方案


问题是您entry_set在这一行中使用:

toppings = name.entry_set.order_by('topping')

并且您必须使用 小写的类名(例如, ?)在foo_set哪里footoppings

toppings = name.toppings_set.order_by('topping')

推荐阅读