Trying to access my json page I get this error!
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'.
I have a Many to Many relationship with my models:
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")
And these serializers:
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',)
How can I get round this? RelatedManager tells me something is disagreeing with my M2M link, but why/how? I couldn't see anything here about Attribute Errors.
This question seems related, but setting many=False
doesn't do anything.
AttributeError with Django REST Framework and MongoEngine
In that question they set many=False
. You do have a Many-to-Many, so set many=True
It's that simple.
In fact if you look closely, that's how the example shows you to do it:
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')
See how the tracks listing field has the many=True
attribute? Do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With