【问题标题】:Django Rest Framework: URL endpoint to add 'Favorite/Like/Rate' functionality when using Viewsets?Django Rest Framework:使用视图集时添加“收藏/喜欢/评分”功能的 URL 端点?
【发布时间】:2020-06-13 18:37:18
【问题描述】:

我创建了一个“食谱”视图集,我希望人们能够收藏不同的食谱。

我的 Viewset 非常简单,看起来像这样:

class RecipeViewset(ListModelMixin, RetrieveModelMixin, GenericViewSet):
    queryset = Recipe.objects.filter(enabled=True)
    serializer_class = RoutineSerializer

我的 urls.py 正在使用 SimpleRouter(现在我没有任何 url 模式,所以我将其留空:

urlpatterns = []
router = routers.SimpleRouter()
router.register('recipes', views.RecipeViewset, basename='recipes')
urlpatterns += router.urls

这会为列表和详细信息创建 2 个端点:

www.example.com/recipes
www.example.com/recipes/1

对于收藏食谱的端点的外观,我有几个选择:

www.example.com/recipes/1/favorite
www.example.com/recipes/favorite/1
www.example.com/favorite/recipes/1
www.example.com/recipes-favorite/1

哪种方法是最好的,Django 是否提供了一种简单的方法来实现这一点?

可以使用 Viewset @action 装饰器吗?

PS:用户将在标头中发送 Auth Token,因此不需要在 URL 中发送。

【问题讨论】:

  • 您如何设置端点路径?你能告诉我们你的urls.py吗?

标签: django django-rest-framework


【解决方案1】:

这似乎是一个很可能会用意见而不是事实来回答的问题,因为 API 设计对开发人员和消费者之间的合同非常主观。

这里有一些API子资源设计技巧的链接:[1][2]

但是,要使用 DRF 中的嵌套资源,我认为您应该使用 drf-nested-routers,因为它们提供了与您已有的类似的接口。

为此,我认为创建此端点www.example.com/recipes/1/favorite 会更容易,因为它已经在文档中提供了示例并且似乎工作得很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2017-12-17
    相关资源
    最近更新 更多