尝试在django中获得manytomany
关系,但我收到以下错误 -
尝试在序列化程序GenreSerializer上获取字段name
的值时,获得AttributeError。 序列化程序字段可能名称不正确,并且与Movie实例上的任何属性或键都不匹配。 原始异常文本是:'Movie'对象没有属性'name'。
这里有一个类似的答案,建议设置many=True
,但它不起作用 -
Attribute error when attempting to get a value for field
models.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
serializers.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')
urls.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)
views.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
答案 0 :(得分:2)
与您的其他问题类似,您在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