python - 对象没有属性“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
先感谢您!
解决方案
问题是您entry_set
在这一行中使用:
toppings = name.entry_set.order_by('topping')
并且您必须使用
小写的类名(例如, ?)在foo_set
哪里foo
toppings
toppings = name.toppings_set.order_by('topping')
推荐阅读
- kubernetes - POD 的 GKE (Google Kubernetes Engine) 网络流量监控,用于详细的基于字节的计费
- regex - 如何替换字符串中的所有内容,但一组子字符串?
- docker - Docker 的 Dotnet 构建崩溃
- asp.net - Asp Core + EPPLUS 怎么做分页符?
- vertica - 在vertica中合并角色
- python - 将一个列表中的值分配给另一个列表
- html - 为什么分页符不适用于 CSS 显示网格?
- javascript - 以 1 而不是 0 开始计数并转换为 ajax
- c - “scanf”作为while循环中的条件
- python - 如何使用“真实”案例测试我的自然语言处理模型?