尝试序列化我的模型。我希望端点应显示数据及其相关数据(外键)。
但是我遇到一个错误,那就是
TypeError: 'Author' object is not iterable
这些是我的序列化器类
from rest_framework import serializers
from . models import Author, Article, Category
class AuthorSerializers(serializers.ModelSerializer):
class Meta:
model = Author
fields = '__all__'
class CategorySerializers(serializers.ModelSerializer):
class Meta:
model = Category
fields = '__all__'
class ArticleSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField(many=True)
category = serializers.StringRelatedField(many=True)
class Meta:
model = Article
fields = '__all__'
这是我的模特
from django.db import models
from django.contrib.auth.models import User
class Author(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE)
detail = models.TextField()
def __str__(self):
return self.name.username
class Category(models.Model):
name = models.CharField(max_length=100)
class Article(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='author')
title = models.CharField(max_length=200)
body = models.TextField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
这些是我的观点:
class ArticleListCreateGet(ListAPIView, CreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleSingle(RetrieveAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
lookup_field = 'pk'
# This is delete/update method
class ArticleDeleteUpdate(DestroyAPIView, UpdateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
lookup_field = 'pk'
这些是我的网址
path('api/v1/article', views.ArticleListCreateGet.as_view(), name='article'),
path('api/v1/article/<int:pk>/detail', views.ArticleSingle.as_view(), name='article-single'),
path('api/v1/article/<int:pk>', views.ArticleDeleteUpdate.as_view(), name='article-delete-update'),
答案 0 :(得分:0)
在您的情况下,Article
具有指向Author
和Category
的外键。因此,每篇文章只有一个作者或类别,您无需在many=True
中设置ArticleSerializer
。
from rest_framework import serializers
from . models import Article
class ArticleSerializer(serializers.ModelSerializer):
author = serializers.StringRelatedField()
category = serializers.StringRelatedField()
class Meta:
model = Article
fields = '__all__'