- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个小项目来练习 Django REST Framework(以及后来的 React 前端),然后再将我学到的技能应用到更大的公司项目中。
该项目是一个后端 API,允许人们查看《费城永远阳光明媚》每一集中主角犯下的潜在犯罪和侵权行为。为此,我做了this GitHub 存储库并在其中放入 Django 项目。
我发现自己在浏览器调试 View 中遇到错误,当我为网站添加新模型/序列化器/ View 时,我不太能弄清楚:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/characters/
Django Version: 1.10.6
Python Version: 3.6.0
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'offense_api.apps.OffenseApiConfig']
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:
File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
42. response = get_response(request)
File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)
File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view
58. return view_func(*args, **kwargs)
File "/Users/person/Workspace/IASIP_API/offense_api/views.py" in character_list
70. return JsonResponse(serializer.data, safe=False)
File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/rest_framework/serializers.py" in data
729. ret = super(ListSerializer, self).data
File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/rest_framework/serializers.py" in data
262. self._data = self.to_representation(self.instance)
File "/Users/person/.virtualenvs/IASIP/lib/python3.6/site-packages/rest_framework/serializers.py" in to_representation
647. self.child.to_representation(item) for item in iterable
Exception Type: TypeError at /characters/
Exception Value: 'ModelBase' object is not iterable
这只发生在“角色”页面上,该页面应该与我的其他 ListView (季节列表)相同。
序列化器.py
from rest_framework import serializers
from offense_api.models import Season, Episode, Character
class SeasonSerializer(serializers.ModelSerializer):
episodes = serializers.StringRelatedField(many=True)
class Meta:
model = Season
fields = ('season_number', 'episodes')
class EpisodeSerializer(serializers.ModelSerializer):
class Meta:
model = Episode
fields = ('episode_number', 'episode_title', 'episode_season')
class CharacterSerializer(serializers.ModelSerializer):
class Meta:
model = Character
fields = ('character_legal_first_name', 'character_legal_last_name', 'character_preferred_name',)
模型.py
from django.db import models
class Season(models.Model):
season_created = models.DateTimeField(auto_now_add=True)
season_number = models.IntegerField(unique=True)
def __unicode__(self):
return self.season_number
def __str__(self):
return str(self.season_number)
class Episode(models.Model):
episode_season = models.ForeignKey(Season, related_name='episodes', on_delete=models.CASCADE)
episode_created = models.DateTimeField(auto_now_add=True)
episode_number = models.IntegerField()
episode_title = models.CharField(max_length=300, default='')
def __unicode__(self):
return '%d. %d' % (self.episode_season.season_number, self.episode_number)
def __str__(self):
return '%d. %d' % (self.episode_season.season_number, self.episode_number)
class Meta:
unique_together = ('episode_season', 'episode_number')
ordering = ('episode_number',)
class Character(models.Model):
character_created = models.DateTimeField(auto_now_add=True)
character_legal_first_name = models.CharField(max_length=50, default='', null=True)
character_legal_last_name = models.CharField(max_length=100, default='', null=True)
character_preferred_name = models.CharField(max_length=150, default='', primary_key=True)
def __unicode__(self):
return self.character_preferred_name
def __str__(self):
return self.character_preferred_name
class Meta:
ordering = ('character_preferred_name',)
Views.py
from django.http import HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from offense_api.models import Episode, Season, Character
from offense_api.serializers import EpisodeSerializer, SeasonSerializer, CharacterSerializer
@csrf_exempt
def season_list(request):
"""
List all seasons, or create a new one.
:param request:
:return:
"""
if request.method == 'GET':
seasons = Season.objects.all()
serializer = SeasonSerializer(seasons, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = SeasonSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def season_detail(request, pk):
"""
Retrieve, update, or delete a season.
:param request:
:param pk:
:return:
"""
try:
season = Season.objects.get(pk=pk)
except Season.DoesNotExist:
return HttpResponse(status=404)
if request.method == 'GET':
serializer = SeasonSerializer(season)
return JsonResponse(serializer.data)
elif request.method == 'PUT':
data = JSONParser().parse(request)
serializer = SeasonSerializer(season, data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse(serializer.errors, status=400)
elif request.method == 'DELETE':
season.delete()
return HttpResponse(status=204)
@csrf_exempt
def character_list(request):
"""
List all characters, or create a new one.
:param request:
:return:
"""
if request.method == 'GET':
characters = Character.objects.all()
serializer = CharacterSerializer(Character, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = CharacterSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
Urls.py
from django.conf.urls import url
from offense_api import views
urlpatterns = [
url(r'^seasons/$', views.season_list),
url(r'^seasons/(?P<pk>[0-9]+)/$', views.season_detail),
url(r'^characters/$', views.character_list),
]
需要修改哪些内容才能避免此错误?
最佳答案
在views.py中,您将类Character传递给序列化器。您应该传递数据字符。
也不要使用首选名称作为主键,它很容易变得不唯一
关于python - 类型错误 : "ModelBase is not iterable",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43055952/
我正在尝试表达以下内容: 给定一个矩阵和两个索引增量,返回矩阵中所有数字的四倍体:沿行,列或对角线的四倍体。 use std::iter::Iterator; use std::iter::Peeka
假设我们有以下类组成角色 Iterable : class Word-Char does Iterable { has @.words; method !pairize($item)
我编写了一个 ADT 排序二叉树,其功能如下: public Iterator getInorderIterator(){ return new InorderIterator(); } 有效
在包装(内部)迭代器时,通常必须将 __iter__ 方法重新路由到底层可迭代对象。考虑以下示例: class FancyNewClass(collections.Iterable): def
尽管如此,我遍历了以下 NSSet , NSMutableArray , NSFastEnumeration文档,我找不到下面提到的场景的令人满意的来源: 此处,NSMutableArray、NSAr
我发现在 Python 中 collections.Iterable 和 typing.Iterable 都可以用于类型注释和检查对象是否可迭代,即 >isinstance(obj, collecti
我想拆分实现 Iterator 的对象的输出分为两个实现 Iterator 的对象和 Iterator .由于其中一个输出的迭代次数可能比另一个多,因此我需要缓冲 Iterator 的输出。 (因为我
我正在尝试用 Rust 编写一个简单的迭代器: #[derive(Debug)] pub struct StackVec { storage: &'a mut [T], len: us
什么意思: Separator.Iterator.Element == Self.Iterator.Element.Iterator.Element 在this (Swift 标准库)swift 实例
调用 anIterable.iterator() 会返回新的迭代器还是现有的迭代器?它依赖于 Iterable 的实现吗? 更具体地说,以下代码是否按预期工作(即内部循环将从头开始迭代)? for (
我正在尝试转换 &str 的矢量对成一个 HashMap使用以下代码片段: use std::collections::HashMap; fn main() { let pairs = vec!(
这将使安全地迭代同一元素两次成为可能,或者为在项目类型中迭代的全局事物保持某种状态。 类似于: trait IterShort where Self: Borrow, { type I
我在 String 的字符上使用迭代器: pub fn is_yelling(message: &str) -> bool { let letters = message.chars().fi
这将使安全地迭代同一元素两次成为可能,或者为在项目类型中迭代的全局事物保持某种状态。 类似于: trait IterShort where Self: Borrow, { type I
要在 Rust 中实现迭代器,我们只需要实现 next 方法,如 in the documentation 所解释的那样.但是,Iterator 特征 has many more methods .
我正在为多个结构实现 Iterator 特性并遇到了一些问题。为什么为 Rows 实现 Iterator 显示错误?这是一个链接:link to playground 基本上为什么这不起作用? str
我将集合转储到磁盘上。当请求时,应该检索这些集合(没问题)和 iterator应该为它构建返回对检索到的值的引用。 iterator之后被丢弃了,我不再需要收藏了。我也希望它被删除。 到目前为止我尝试
我正在尝试为实现特征的结构实现默认迭代器。我的特征称为 DataRow,代表一行表格单元格,如下所示: pub trait DataRow { // Gets a cell by index
Rust 中是否有提供 iter() 的 Trait方法?我只找到了特征 IntoIterator ,供应into_iter() . 这里要明确一点:我不想要 Iterator特性,提供 next()
我想在迭代器上定义一个 .unique() 方法,使我能够在没有重复的情况下进行迭代。 use std::collections::HashSet; struct UniqueState {
我是一名优秀的程序员,十分优秀!