AttributeError with Django REST Framework and a ManyToMany relationship

断了今生、忘了曾经 提交于 2019-12-07 09:38:50

问题


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


回答1:


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.




回答2:


I had a similar issue when I missed out on specifying the related_name attribute to the definition of ForeignKeyField pointing to the Album model.



来源:https://stackoverflow.com/questions/28108600/attributeerror-with-django-rest-framework-and-a-manytomany-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!