Django休息序列化器不会与多对多的关系工作

时间:2018-01-18 04:52:50

标签: django python-3.x django-rest-framework

我试图创建一个基于简单看板的个人项目,模型任务与模型板有关系。

当我尝试renderize它时,我得到的项目:title和slug,但是,与模型板的关系缺失,有人可以帮我解决这个错误,我做错了什么?

OBS:我知道,这里的stackoverflow有很多帖子都有相同的主题,但不幸的是我找不到解决方案:/

这是我的型号代码:

class Board(models.Model):
    BACKLOG = 'Backlog'
    PROCESS = 'In progress'
    QA = 'QA'
    COMPLETE = 'Complete'
    _status = ((BACKLOG, 'Backlog'), (PROCESS, 'In progress'), (QA, 'QA'),
           (COMPLETE, 'Complete'))

    LOW = 'Low'
    NORMAL = 'Normal'
    HIGH = 'High'
    _priority = ((LOW, 'Low'), (NORMAL, 'Normal'), (HIGH, 'High'))
    status = models.CharField(_('Status'), max_length=20, choices=_status,
                          default=BACKLOG,
                          help_text='Selecione o status da task')
    priority = models.CharField(_('Priority'), max_length=20, choices=_priority,
                            default=NORMAL,
                            help_text='Selecione a prioridade da task')
    description = models.TextField()

    class Meta:
        verbose_name = 'Board'
        verbose_name_plural = 'Boards'
        ordering = ['priority',]

    def __str__(self):
        return "{} - {}".format(self.description, self.priority)

class Task(models.Model):
    title = models.CharField(_('Tittle'), max_length=100,
                         help_text='Titulo da task')
    slug = models.SlugField(db_index=True)
    board = models.ManyToManyField(Board)

    class Meta:
        verbose_name = 'Task'
        verbose_name_plural = 'Tasks'
        ordering = ['title',]

    def __str__(self):
        return "{}".format(self.title)

在我的序列化程序文件中,我有以下代码:

class BoardSerializer(serializers.ModelSerializer):
    class Meta:
        model = Board
        fields = ('description', 'priority', 'status')

class TaskSerializer(serializers.ModelSerializer):
    boards = BoardSerializer(many=True, read_only=True)
    class Meta:
        model = Task
        fields = ('title', 'slug', 'boards')

在我看来,我有这段代码:

class TaskList(generics.ListCreateAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer

以下是呈现的项目:

[
  {
    "title": "create the login page",
    "slug": "create-the-login-page"
  }
]

1 个答案:

答案 0 :(得分:0)

class Task(models.Model):
    ...
    board = models.ManyToManyField(Board)

更改为

class Task(models.Model):
    ...
    boards = models.ManyToManyField(Board)

然后运行:

 python manage.py makemigrations
 python manage.py migrate

在终端。 由于模型中的字段名称必须与序列化程序中的字段名称相同