字段' id'期待一个数字,但获得了category.id'

发布于 2025-02-11 06:06:58 字数 2570 浏览 2 评论 0原文

我正在尝试在数据库中创建类别,但是当我尝试使用输入的模型访问类别时。它向我展示了这个错误: 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

被翻牌 2025-02-18 06:06:58

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 the category from your key word arguments.
If you only want to filter posts with published category name only, you can category__name="Published".

Not entirely sure if that answers your question so comment if thats not it.

寒尘 2025-02-18 06:06:58

您的问题在这里:

.filter(category='published')

您正在尝试filter a querySet post对象 category 。但是类别foreferkey字段,仅接受id> id类别对象。您正在尝试将其传递字符串 - '已发布'。不可能那样。

Your problem is here:

.filter(category='published')

You are trying to filter a QuerySet of Post objects by category. But category is a ForeignKey field that accepts only id or Category objects. You are trying to pass there string - 'published'. It cannot be that way.

ら栖息 2025-02-18 06:06:58
class CatListView(ListView):
    template_name = "Blog/category.html"
    context_object_name = 'catlist'
    ordering = ['-date_posted']
    paginate_by = 100

    def get_queryset(self):
        return Post.objects.filter(category__name=self.kwargs['category'])

    def get_context(self, **kwargs):
      context = super().get_context(**kwargs)
      paginator = self.get_paginator()
      context.update({
        'cat': self.kwargs['category'],
        'posts': paginator.get_page(self.kwargs[self.page_kwarg]).object_list,
      })
      return context
      

get_queryset将在分页之前过滤模型。然后在get_context中,paginator.get_page将获得正确的页面(基于url param self.page_kwarg,默认情况下是<代码>?page = 2 ),并以最新结果更新上下文字典。

有关基于类的视图方法的参考,我建议您查看: https://ccbv.co.uk/

class CatListView(ListView):
    template_name = "Blog/category.html"
    context_object_name = 'catlist'
    ordering = ['-date_posted']
    paginate_by = 100

    def get_queryset(self):
        return Post.objects.filter(category__name=self.kwargs['category'])

    def get_context(self, **kwargs):
      context = super().get_context(**kwargs)
      paginator = self.get_paginator()
      context.update({
        'cat': self.kwargs['category'],
        'posts': paginator.get_page(self.kwargs[self.page_kwarg]).object_list,
      })
      return context
      

The get_queryset will filter the Post models before they are paginated. Then inside the get_context, the paginator.get_page will get the correct page (based on the url param self.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/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文