django 创建多个字段超链接

ndasle7k  于 11个月前  发布在  Go
关注(0)|答案(2)|浏览(86)
  • 我需要在API中更改类别;我的类别和书籍模型很多。*

代码:

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": [
        "http://127.0.0.1:8000/category/2/"
    ],

h4cxqtbf

h4cxqtbf1#

你可以修改字典以适应你的需要。我不确定是否会有多个类别,或者你想如何处理多个类别,但这个概念仍然存在。

manytomany = "http://127.0.0.1:8000/category/"
for category in outputDict["categories"]:
    manytomany += str(category) + "/"

outputDict["categories"] = manytomany

字符串

yyhrrdl8

yyhrrdl82#

您可以修改序列化程序以使用“HyperlinkedRelatedField”而不是默认的“PrimaryKeyRelatedField”。这将生成带有到相关类别对象的url的输出
所以BookSerializer应该是这样的:

class BookSerializer(serializers.ModelSerializer):

    categories = serializers.HyperlinkedRelatedField(
    many=True,
    read_only=True,
    view_name='category-detail'  # instead of 'category-detail' use the actual name of your category detail view in your URLs.
)
    class Meta:
        model = Book
        fields = ('id','isbn','title','content','price','authors','categories','price_after_discount')

字符串
我希望这对你有帮助。

相关问题