DRF-嵌套路由器-在POST / PUT / PATCH上创建/更新嵌套对象

时间:2018-07-16 07:34:11

标签: python django django-rest-framework nested-routes drf-nested-routers

我目前正在启动一个简单的Task App,并且正在使用Django 2.0.7,DRF 3.8.2和drf-nested-routes 0.90.2

我有这些型号:

class Client(TimeStampedModel):
    """
    This model describes a client for the railroader. It can be created by the manager in the back office
    We have at least one internal Client, which is Seelk, for internal projects
    """
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(null=True)
    is_active = models.BooleanField(default=True)

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

class Project(TimeStampedModel):
    """
    This model represents a project for a client, which we are gonna track actions on
    """
    client = models.ForeignKey(
        'railroader.Client', on_delete=models.PROTECT, related_name='projects')
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(null=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):
        return "{} for client {}".format(self.name, self.client.name)

因此,按照drf-nested-router的文档,我像这样设置我的序列化器:

class ClientSerializer(serializers.ModelSerializer):
    class Meta:
        model = Client
        fields = ("id", "name", "description", "is_active", "projects")


class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ("id", "name", "description", "is_active")

我的观点集是这样的:

class ClientViewset(viewsets.ModelViewSet):
    serializer_class = ClientSerializer
    permission_classes = (permissions.IsAuthenticated, AccountPermission)

    def get_queryset(self):
        queryset = Client.objects.all()
        is_active = self.request.query_params.get("is_active")
        if is_active:
            queryset = queryset.filter(is_active=is_active)
        return queryset


class ProjectViewset(viewsets.ModelViewSet):
    serializer_class = ProjectSerializer
    permission_classes = (permissions.IsAuthenticated, AccountPermission)

    def get_queryset(self):
        queryset = Project.objects.filter(client=self.kwargs["client_pk"])
        is_active = self.request.query_params.get("is_active")
        if is_active:
            queryset = queryset.filter(is_active=is_active)
        return queryset

最后,我的网址是这样的:

router = routers.SimpleRouter()
router.register(r"clients", viewsets.ClientViewset, base_name="clients")

projects_router = routers.NestedSimpleRouter(router, r"clients", lookup="client")
projects_router.register(r"projects", viewsets.ProjectViewset, base_name="projects")
urlpatterns = [
    re_path(r"^", include(router.urls)),
    re_path(r"^", include(projects_router.urls))
]

使用此设置,我可以拥有所需的嵌套路由,但是如果我在嵌套路由上发布,则无法使用路由来创建新对象。

我已经在github上看到了一个关于它的问题,但是就像2年前一样,我想知道是否有人知道该怎么做。

谢谢。

1 个答案:

答案 0 :(得分:0)

发现我只是忘记了在序列化器的DRF create方法中返回实例不会在base中创建对象。最后,我有了这个序列化器:

class ProjectSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        client = Client.objects.get(pk=self.context["view"].kwargs["client_pk"])
        validated_data["client"] = client
        return Project.objects.create(**validated_data)

    class Meta:
        model = Project
        fields = ("id", "name", "description", "is_active")