【问题标题】:Django Rest Framework get a parameter from the URL, ignore the one in bodyDjango Rest Framework 从 URL 获取参数,忽略正文中的参数
【发布时间】:2016-07-08 00:49:44
【问题描述】:

我正在使用 Django 1.9 和 Django Rest Framework 3.3。我有传入的 POST 请求,可以是 dictlist,访问相同的 API 端点。端点 URL 如下所示:/api/children/3/classes。这个3 表示孩子的ID。

我传入的 POST 请求如下所示:

{
   "name": "Mathematics",
   "teacher": "Mr. Kabbatt",
   "school": "High School"
   "child": 2
}

在这种情况下,我给出了一个字典,但它也可以是一个字典数组(列表)。

如何强制 Django Rest Framework 忽略在 POST 正文中设置的 child 参数并使用 URL 中的参数?我正在使用ListCreateAPIView 泛型,我已经能够在get_queryset() 方法中获得child 参数。在序列化程序方面,我使用了来自 DRF 的简单 ModelSerializer,其中包含所有字段。

【问题讨论】:

  • 你能添加你的视图代码吗?

标签: python django django-rest-framework


【解决方案1】:

如果我对您的理解正确,您想使用 url 提供的参数覆盖请求正文上的 child 值。

def post(self, request, *args, **kwargs):
    # django passes params from url in kwargs
    # e.g. {id: 3} or {child: 3}, not sure what your url calls it
    if request.data.__class__ is dict:
        request.data['child'] = kwargs['id']
    elif request.data.__class__ is list:
        # dunno what your setup looks like here
        for i in request.data:
            request.data[i]['child'] = kwargs['id']
    self.create(request, *args, **kwargs)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2017-01-09
    • 2014-02-13
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多