无法在Django rest框架中显示外键关系

时间:2016-10-11 10:17:28

标签: django django-rest-framework

我有一个模型Project,Tasks和Project有很多任务,我试图列出每个项目下的所有任务。

GET /api/project/ 

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "id": 2,
        "name": "Project 2",
        "task": [
            3
        ]
    },
    {
        "id": 1,
        "name": "Project 1",
        "task": [
            4,
            2,
            1
        ]
    }
]

我无法显示每个任务,任务名称,说明,状态的详细信息..等等

这是我的Serializer

from rest_framework.serializers import ModelSerializer
from api.models import Project, Task


class ProjectSerializer(ModelSerializer):
    class Meta:
        model = Project
        fields = (
            'id',
            'name',
            'task'
            )


class TaskSerializer(ModelSerializer):

    class Meta:
        model = Task

这是我的模特

class Project(models.Model):

    # Fields
    user = models.ForeignKey(User)
    name = models.CharField(max_length=255)

    # Relationship Fields
    #user = models.ForeignKey(settings.AUTH_USER_MODEL, )
    user = models.ForeignKey(User)

    class Meta:
        ordering = ('-created',)

    def __unicode__(self):
        return u'%s' % self.name


class Task(models.Model):

    # Fields
    name = models.CharField(max_length=255)

    # Relationship Fields
    project = models.ForeignKey('Project', related_name='task' )

    class Meta:
        ordering = ('-created',)

    def __unicode__(self):
        return u'%s' % self.name

1 个答案:

答案 0 :(得分:1)

详细了解嵌套序列化程序http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects。您需要将ProjectSerializer添加到from rest_framework.serializers import ModelSerializer from api.models import Project, Task class TaskSerializer(ModelSerializer): class Meta: model = Task class ProjectSerializer(ModelSerializer): task = TaskSerializer(many=True) class Meta: model = Project fields = ( 'id', 'name', 'task' )

$('[data-toggle=tab]').click(function(e){
    if($(this).parent().hasClass('active')){

    e.preventDefault();
    e.stopPropagation();

        $(this).parent().removeClass('active');

        $($(this).attr("href")).removeClass('active');
        $($(this).attr("href")).removeClass('in');

        $(this).attr("aria-expanded", false);
    }
})