【问题标题】:how can make new object in django-restful-framework by post method?如何通过 post 方法在 django-restful-framework 中创建新对象?
【发布时间】:2021-07-24 16:40:48
【问题描述】:

我有这个型号

class Product(models.Model):
    name = models.CharField(max_length=50)
    price = models.PositiveIntegerField()

我想在 django 的 restframework 中使用 post 方法创建一个新对象,但我不知道该怎么做,请帮助我

@api_view(['POST'])
def create_product(request):
    *******
    return Response({
        *******
    }, status=status.HTTP_201_CREATED)

我应该用 **** 替换 django 代码,请帮帮我

【问题讨论】:

    标签: django django-rest-framework django-templates django-rest-viewsets


    【解决方案1】:

    简单易懂。最喜欢你在 python 中创建新类对象的方式。

    @api_view(['POST'])
    def create_product(request):
        p = Product(name='sth', price=1)
        p.save()
        return Response({
             # um... now we should start talking about serializers.
        }, status=status.HTTP_201_CREATED)
    

    请注意,方法 save() 不会返回创建的对象,因此如果您需要创建的对象,请遵循模式。

    据我所知,发送模型对象作为响应(甚至获取对象数据作为请求)的最佳方式是使用序列化程序。 Serilizer 通常意味着更改数据的格式。在 django 中,我们可以使用序列化程序作为将模型对象转换为 json 的工具。 (如果您不熟悉 json 数据格式,它就像一本字典,既可读又易于编程。) 当然你也可以像这样创建自己的 json 数据(或字典):

    data = {}
    data['name'] = p.name
    return Respond(data=data, 
    status=status.HTTP_201_CREATED)
    

    但是为什么要麻烦呢?

    这里是 drf 的序列化程序文档的链接: https://www.django-rest-framework.org/api-guide/serializers/

    享受吧!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      • 2021-08-01
      • 2016-10-24
      相关资源
      最近更新 更多