I need to change categories in API; my category and books models are manytomany.
Code:
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')
Output:
{
"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
]
},
But I need:
"categories": [
"http://127.0.0.1:8000/category/2/"
],
You can modify the dictionary to fit your needs. I'm not sure if there will be multiple categories, or how you want to deal with multiple of them, but the concept still stands.
manytomany = "http://127.0.0.1:8000/category/"
for category in outputDict["categories"]:
manytomany += str(category) + "/"
outputDict["categories"] = manytomany