【问题标题】:Read, update, and create with Django REST Framework使用 Django REST Framework 读取、更新和创建
【发布时间】:2015-05-21 15:15:54
【问题描述】:

我有一个 ViewSet 定义为

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer

并将我的网址定义为

router = routers.DefaultRouter()

router.register(r'items', ItemViewSet)

urlpatterns = patterns('',
    url(r'^api/', include(router.urls)),

可浏览的 API 工作正常。

我想用 $.ajax() 读取和发送 json。我怎样才能使用我的 ViewSet 来做到这一点?我可以用$.ajax({url: '/api/items/'}) 之类的东西检索我的所有项目,但我不想硬编码网址。如果我想编辑特定项目怎么办?当我没有保存页面的命名 url 时,我该怎么办?

【问题讨论】:

    标签: ajax django rest django-rest-framework django-rest-auth


    【解决方案1】:

    阅读有关 routers 的 DRF 文档

    简单地说,你有:

    GET     /api/items/     #list the items
    POST    /api/items/     #create new item
    GET     /api/items/1/   #detail info about item with id=1
    PUT     /api/items/1/   #update item with id=1
    PATCH   /api/items/1/   #partial-update item with id=1
    DELETE  /api/items/1/   #delete item with id=1
    

    【讨论】:

    • 但我没有命名网址。我无法对所有网址进行硬编码
    • 您已将 urls.try 命名为 reverse('item-list')reverse('item-detail', args=[1])。此 url 可以传递给 javascript,以免被硬编码。
    猜你喜欢
    • 1970-01-01
    • 2020-11-11
    • 2019-05-29
    • 2016-05-03
    • 2023-03-31
    • 2021-06-28
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    相关资源
    最近更新 更多