在 /books/ 处配置不当 字段名称“Published_date”对于模型“Books”无效

发布于 2025-01-10 13:11:15 字数 4969 浏览 0 评论 0原文

我正在构建这个rest api,它从数据库获取数据并显示数据库中有关书籍的所有字段。

models.py 代码:

class Books(models.Model):
   Name = models.CharField(max_length=250)
   Author = models.ForeignKey('Authors', on_delete=models.CASCADE, default=None)
   Published_Date = models.DateField(blank=False)
   Pages = models.IntegerField()
   critics = models.IntegerField(default=0)

   def __str__(self) -> str:
      return self.Name

serializer.py 代码:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
       model = Books
       fields = ['Name', 'Author', 'Published_date', 'Pages', 'critics']

urls.py 代码:

urlpatterns = [
    path('books/', views.BookList.as_view()),
    path('Bdetails/<str:pk>', views.BookDetail.as_view()),
]

views.py 代码:

class BookList(generics.ListCreateAPIView):
    queryset = Books.objects.all()
    serializer_class = BookSerializer


class BookDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Books.objects.all()
    serializer_class = BookSerializer

回溯:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/books/

Django Version: 3.2.9
Python Version: 3.9.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'genebox',
 'rest_framework']

Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in 
    _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in 
    wrapped_view return view_func(*args, **kwargs)
  File "C:\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 480, in 
    raise_uncaught_exception 
  raise exc
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Python39\lib\site-packages\rest_framework\generics.py", line 239, in get
    return self.list(request, *args, **kwargs)
  File "C:\Python39\lib\site-packages\rest_framework\mixins.py", line 43, in list
    return self.get_paginated_response(serializer.data)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 745, in data
    ret = super().data
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 246, in data
    self._data = self.to_representation(self.instance)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 663, in 
    to_representation
    return [
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 664, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 500, in 
    to_representation
    for field in fields:
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 361, in 
    _readable_fields
    for field in self.fields.values():
  File "C:\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__
   res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 349, in fields
   for key, value in self.get_fields().items():
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 1053, in get_fields
   field_class, field_kwargs = self.build_field(
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 1199, in 
   build_field
   return self.build_unknown_field(field_name, model_class)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 1317, in 
   build_unknown_field
   raise ImproperlyConfigured(


Exception Type: ImproperlyConfigured at /books/
Exception Value: Field name `Published_date` is not valid for model `Books`.

我们将不胜感激您的帮助

I am building this rest api which gets data from database and shows all the fields regarding the books in database.

models.py code:

class Books(models.Model):
   Name = models.CharField(max_length=250)
   Author = models.ForeignKey('Authors', on_delete=models.CASCADE, default=None)
   Published_Date = models.DateField(blank=False)
   Pages = models.IntegerField()
   critics = models.IntegerField(default=0)

   def __str__(self) -> str:
      return self.Name

serializer.py code:

class BookSerializer(serializers.ModelSerializer):
    class Meta:
       model = Books
       fields = ['Name', 'Author', 'Published_date', 'Pages', 'critics']

urls.py code:

urlpatterns = [
    path('books/', views.BookList.as_view()),
    path('Bdetails/<str:pk>', views.BookDetail.as_view()),
]

views.py code:

class BookList(generics.ListCreateAPIView):
    queryset = Books.objects.all()
    serializer_class = BookSerializer


class BookDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = Books.objects.all()
    serializer_class = BookSerializer

traceback:

Environment:

Request Method: GET
Request URL: http://127.0.0.1:8000/books/

Django Version: 3.2.9
Python Version: 3.9.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'genebox',
 'rest_framework']

Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in 
    _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Python39\lib\site-packages\django\views\decorators\csrf.py", line 54, in 
    wrapped_view return view_func(*args, **kwargs)
  File "C:\Python39\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 480, in 
    raise_uncaught_exception 
  raise exc
  File "C:\Python39\lib\site-packages\rest_framework\views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Python39\lib\site-packages\rest_framework\generics.py", line 239, in get
    return self.list(request, *args, **kwargs)
  File "C:\Python39\lib\site-packages\rest_framework\mixins.py", line 43, in list
    return self.get_paginated_response(serializer.data)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 745, in data
    ret = super().data
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 246, in data
    self._data = self.to_representation(self.instance)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 663, in 
    to_representation
    return [
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 664, in <listcomp>
    self.child.to_representation(item) for item in iterable
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 500, in 
    to_representation
    for field in fields:
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 361, in 
    _readable_fields
    for field in self.fields.values():
  File "C:\Python39\lib\site-packages\django\utils\functional.py", line 48, in __get__
   res = instance.__dict__[self.name] = self.func(instance)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 349, in fields
   for key, value in self.get_fields().items():
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 1053, in get_fields
   field_class, field_kwargs = self.build_field(
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 1199, in 
   build_field
   return self.build_unknown_field(field_name, model_class)
  File "C:\Python39\lib\site-packages\rest_framework\serializers.py", line 1317, in 
   build_unknown_field
   raise ImproperlyConfigured(


Exception Type: ImproperlyConfigured at /books/
Exception Value: Field name `Published_date` is not valid for model `Books`.

Your Help will be appreciated

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

猫弦 2025-01-17 13:11:15

您的字段名为 Published_Date,带有大写 D,而不是 Published_date。但通常字段不是用大写字母书写,而是用snake_case书写,并且模型名称是单数,所以Book,不是书籍,和作者,而不是作者

class Book(models.Model):
   name = models.CharField(max_length=250)
   author = models.ForeignKey('Author', on_delete=models.CASCADE, default=None)
   published_date = models.DateField()
   pages = models.IntegerField()
   critics = models.IntegerField(default=0)

   def __str__(self) -> str:
      return self.name

Your field is named Published_Date with an uppercase D, not Published_date. But normally fields are not written with uppercases, but in snake_case, and model names are singular, so Book, not Books, and Author, not Authors:

class Book(models.Model):
   name = models.CharField(max_length=250)
   author = models.ForeignKey('Author', on_delete=models.CASCADE, default=None)
   published_date = models.DateField()
   pages = models.IntegerField()
   critics = models.IntegerField(default=0)

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