You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Django REST Framework中多对多字段改为超链接形式?

调整多对多关系字段返回为URL格式

问题场景

Book与Category为多对多关系,当前API返回的categories字段是分类ID数组,需要改为返回对应分类资源的绝对URL数组。

现有序列化器代码:

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name')

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = ('id','isbn','title','content','price','authors','categories','price_after_discount')

当前输出示例:

{
    "id": 1,
    "isbn": "978-1-4061-9242-1",
    "title": "Energy carry different lot. Back room practice with.",
    "content": "Suddenly various answer author.",
    "price": "7346.00",
    "authors": [1,2],
    "categories": [2]
}

期望输出的categories格式:

"categories": [
    "http://127.0.0.1:8000/category/2/"
]

解决方案

在BookSerializer中显式定义categories字段,使用DRF的HyperlinkedRelatedField生成资源URL:

from rest_framework import serializers

class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = Category
        fields = ('id', 'name')

class BookSerializer(serializers.ModelSerializer):
    # 定义categories为超链接关联字段
    categories = serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='category-detail'  # 替换为你实际的Category详情视图路由名称
    )

    class Meta:
        model = Book
        fields = ('id','isbn','title','content','price','authors','categories','price_after_discount')

注意事项

  • view_name必须与urls.py中配置的Category详情视图的name参数一致,比如路由是path('category/<int:pk>/', CategoryDetailView.as_view(), name='category-detail'),就填category-detail。
  • 若用router.register('category', CategoryViewSet)自动生成路由,默认详情视图名称就是category-detail,可直接使用。
  • 若需要在创建/更新Book时通过URL关联分类,去掉read_only=True并添加queryset=Category.objects.all()。

内容的提问来源于stack exchange,提问作者samydgr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 04:24:53