1

我有一个作者和书籍模型。一位作家有很多书

class Author(Model):
    id = UUIDField(primary_key=True, default=uuid4, editable=False)
    name = CharField(max_length=50)
    email = CharField(max_length=50)

class Book(Model):
    id = UUIDField(primary_key=True, default=uuid4, editable=False)
    name = CharField(max_length=50)
    author = ForeignKey(Author, on_delete=models.CASCADE)

在我的 urls.py

author_router = SimpleRouter()
author_router.register(
    r"author", AuthorViewSet, basename=author
)

nested_author_router = NestedSimpleRouter(author_router, r"author", lookup="author")
nested_author_router.register(r"book", BookViewSet)

在我的searlizers.py

class BookSerializer(ModelSerializer):
    class Meta:
        model = Book
        fields = (
            "id",
            "name",
            "author",
        )
        extra_kwargs = {
            "id": {"required": False},
            "author": {"required": False},
        }

class AuthorSerialzer(ModelSerializer):
        class Meta:
            model = Author
            fields = (
                "id",
                "name",
                "email",
            )
            extra_kwargs = {
                "id": {"required": False},
            }

在views.py

class BookViewSet(GenericViewSet):
    queryset = Book.objects.all()
    serializer_class = BookSerializer


    def create(self, request, author_pk):
        data = request.data
        data["author"] = author_pk
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save() 
        return Response(serializer.data)

由于书籍与作者有关​​,并且我使用的是嵌套路由器,因此 curl 调用看起来像

curl --location --request POST 'localhost:8000/author/1/book' --data '{"name": "Book Name"}'

在我调用序列化方法BookViewSet之前,我最终手动将 author_pk 添加到数据对象中。is_valid有没有办法从 URL 路由或任何更好的方法来指定源?

4

1 回答 1

1

在这种情况下,您可以将 to 传递author_pksave()自动设置新创建书籍的作者 ID,如下所述here

    def create(self, request, author_pk):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save(author_id=author_pk) 
        return Response(serializer.data)
于 2021-09-15T05:58:46.697 回答