字段' id'期待一个数字,但获得了category.id'
我正在尝试在数据库中创建类别,但是当我尝试使用输入的模型访问类别时。它向我展示了这个错误: value at at/category/django/django/em>
django是我使用我使用外国钥匙制作的模型输入的类别。
我尝试了该类别的另一种方法,但也没有起作用。 因此,我认为问题在于db.sqlite3文件或迁移文件中。 我无法删除SQL3 DB文件,我的数据很容易替换。 我认为问题不在设置中。
完整错误:
\Python39\site-packages\django\db\models\lookups.py", line 25, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\related_lookups.py", line 117, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'published'.
这是 views.py 类别的
class CatListView(ListView):
template_name = "Blog/category.html"
context_object_name = 'catlist'
def get_queryset(self):
content = {
'cat': self.kwargs['category'],
'posts': Post.objects.filter(category__name=self.kwargs['category']).filter(category='published')
}
return content
def category_list(request):
category_list = Category.objects.exclude(name='default')
context = {
"category_list": category_list,
}
urls.py
from django.urls import path
from . import views
urlpatterns = [
path("category/<category>/", views.CatListView.as_view(), name="category"),
]
and 类别。html
{% for post in catlist.posts %}
{% endfor %}
更新:
型号
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
werkstoffnummer = models.CharField(max_length=100)
def __str__(self):
return self.werkstoffnummer
def get_absolute_url(self):
return reverse("post-detail", kwargs={"pk": self.pk})
I'm trying to make a category in the DB, but when I try to access the category with the model that entered. it showing me this Error: ValueError at /category/Django/
Django is category I entered with the model I made using a ForeignKey.
I tried a different method for the category but it didn't work either.
so I think the problem is in the db.sqlite3 file or in the migrations files.
I can't delete the sql3 db file, I have data that I can't easy replaces.
I don't think the problem is in the settings.py, I tried to change it before and got the same outcome.
the full Error:
\Python39\site-packages\django\db\models\lookups.py", line 25, in __init__
self.rhs = self.get_prep_lookup()
File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\related_lookups.py", line 117, in get_prep_lookup
self.rhs = target_field.get_prep_value(self.rhs)
File "C:\Users\HPi5\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\models\fields\__init__.py", line 1825, in get_prep_value
raise e.__class__(
ValueError: Field 'id' expected a number but got 'published'.
here is the views.py for the category
class CatListView(ListView):
template_name = "Blog/category.html"
context_object_name = 'catlist'
def get_queryset(self):
content = {
'cat': self.kwargs['category'],
'posts': Post.objects.filter(category__name=self.kwargs['category']).filter(category='published')
}
return content
def category_list(request):
category_list = Category.objects.exclude(name='default')
context = {
"category_list": category_list,
}
the urls.py
from django.urls import path
from . import views
urlpatterns = [
path("category/<category>/", views.CatListView.as_view(), name="category"),
]
and for the category.html
{% for post in catlist.posts %}
{% endfor %}
Update:
models.py
from django.db import models
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(Category, on_delete=models.PROTECT)
werkstoffnummer = models.CharField(max_length=100)
def __str__(self):
return self.werkstoffnummer
def get_absolute_url(self):
return reverse("post-detail", kwargs={"pk": self.pk})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
post.objects.filter(category__name = self.kwargs ['category'])
部分已经是从您的关键字参数中基于category
exterme oft post ewert post。如果您只想仅使用
发布
类别名称过滤帖子,则可以category__name =“已发布”
。不完全确定是否可以回答您的问题,因此如果不是这样,请评论。
The
Post.objects.filter(category__name=self.kwargs['category'])
part alone is already filtering the posts based on thecategory
from your key word arguments.If you only want to filter posts with
published
category name only, you cancategory__name="Published"
.Not entirely sure if that answers your question so comment if thats not it.
您的问题在这里:
您正在尝试
filter
aquerySet
post
对象 category 。但是类别
是foreferkey
字段,仅接受id> id
或类别
对象。您正在尝试将其传递字符串
-'已发布'
。不可能那样。Your problem is here:
You are trying to
filter
aQuerySet
ofPost
objects bycategory
. Butcategory
is aForeignKey
field that accepts onlyid
orCategory
objects. You are trying to pass therestring
-'published'
. It cannot be that way.get_queryset
将在分页之前过滤模型。然后在get_context
中,paginator.get_page
将获得正确的页面(基于url paramself.page_kwarg
,默认情况下是<代码>?page = 2 ),并以最新结果更新上下文字典。有关基于类的视图方法的参考,我建议您查看: https://ccbv.co.uk/
The
get_queryset
will filter thePost
models before they are paginated. Then inside theget_context
, thepaginator.get_page
will get the correct page (based on the url paramself.page_kwarg
which by default is like?page=2
), and update the context dictionary with the latest results.For reference on Class based view methods, I recommend you check out: https://ccbv.co.uk/