尝试访问我的 json 页面时出现此错误!
AttributeError at /project/api/1.json
Got AttributeError when attempting to get a value for field `title` on serializer `TaskSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance.
Original exception text was: 'RelatedManager' object has no attribute 'title'.
我与我的模型有多对多关系:
class Project(models.Model):
owner = models.ForeignKey('auth.User')
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
created_date = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_date = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return self.title
def save(self, **kwargs):
super(Project, self, **kwargs).save()
self.slug = slugify(self.title)
super(Project, self, **kwargs).save()
def create(self):
pass
class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
completed = models.BooleanField(default=False)
project = models.ForeignKey('Project', related_name="tasks")
dependency = models.ManyToManyField('self', through='Dependency', null=True,
blank=True, through_fields=('task', 'sub_task'), symmetrical=False)
def sub_tasks(self, **kwargs):
qs = self.dependency.filter(**kwargs)
for sub_task in qs:
qs = qs | sub_task.sub_tasks(**kwargs)
return qs
def __str__(self):
return self.title
class Dependency(models.Model):
task = models.ForeignKey(Task, related_name="dependency_task")
sub_task = models.ForeignKey(Task, related_name="dependency_sub_task")
这些序列化程序:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'title', 'project', 'completed',)
class ProjectSerializer(serializers.ModelSerializer):
tasks = TaskSerializer()
class Meta:
model = Project
fields = ('id', 'title', 'tasks',)
我怎样才能解决这个问题? RelatedManager 告诉我有什么不同意我的 M2M 链接,但为什么/如何?我看不到任何关于属性错误的 here。
这个问题似乎相关,但设置
many=False
没有任何作用。AttributeError with Django REST Framework and MongoEngine
最佳答案
在那个问题中,他们设置了 many=False
。你确实有一个多对多,那么设置 many=True
就是这么简单。
事实上,如果你仔细观察,这就是示例向你展示的方法:
class TrackListingField(serializers.RelatedField):
def to_representation(self, value):
duration = time.strftime('%M:%S', time.gmtime(value.duration))
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackListingField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
查看轨道列表字段如何具有
many=True
属性?去做。关于python - 带有 Django REST 框架和多对多关系的 AttributeError,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28108600/