gpt4 book ai didi

python - 尝试获取序列化程序上的字段值时出现 AttributeError

转载 作者:行者123 更新时间:2023-12-04 16:09:25 27 4
gpt4 key购买 nike

试图获得 manytomany django 中的关系,但我收到以下错误 -

Got AttributeError when attempting to get a value for field name on serializer GenreSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Movie instance. Original exception text was: 'Movie' object has no attribute 'name'.



这里有一个类似的答案推荐设置 many=True ,但它不起作用 -
Attribute error when attempting to get a value for field

模型.py
class Genre(models.Model):
name = models.CharField(max_length=255,unique=True)

def __unicode__(self):
return self.name

class Movie(models.Model):
mname = models.CharField(max_length=255)
genres = models.ManyToManyField(Genre,related_name='movies')

def __unicode__(self):
return self.mname

序列化程序.py
class GenreSerializer(serializers.ModelSerializer):
class Meta:
model = Genre
fields = ('name','id')

class MovieSerializer(serializers.ModelSerializer):
genres = GenreSerializer(many=True, read_only=True)

class Meta:
model = Movie
fields = ('id','genres','mname')

网址.py
urlpatterns = [
url(r'^genres/$', views.GenreList.as_view()),
url(r'^genres/(?P<pk>[0-9]+)$', views.GenreDetail.as_view()),
]

urlpatterns = format_suffix_patterns(urlpatterns)

View .py
class GenreList(generics.ListCreateAPIView):
queryset = Genre.objects.all()
serializer_class = GenreSerializer


class GenreDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = GenreSerializer

def get_queryset(self):
genres = Genre.objects.get(pk=self.kwargs.get('pk', None))
movies = Movie.objects.filter(genres=genres)
return movies

最佳答案

与您的其他问题类似,您在 GenreDetail 上使用了不正确的序列化程序。看法。您需要为您从 get_queryset 返回的模型类型添加序列化程序。 :

class GenreDetail(generics.RetrieveUpdateDestroyAPIView):
serializer_class = MovieSerializer

def get_queryset(self):
genres = Genre.objects.get(pk=self.kwargs.get('pk', None))
movies = Movie.objects.filter(genres=genres)
return movies

关于python - 尝试获取序列化程序上的字段值时出现 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34443754/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com