1
Guys, I have a question regarding the nested relationship.
When my code gets that way:
class CategoryListSerializer(ModelSerializer):
class Meta:
model = Category
fields = ['id', 'name', 'created_at']
class BookCreateListSerializer(ModelSerializer):
category = CategoryListSerializer()
class Meta:
model = Book
fields = ['id', 'name', 'created_at', 'category']
Returns like this:
When I comment on the category = CategoryListSerializer()
He returns this way:
I want to understand why this behavior and how I can perform POST this way, because when I insert Category it asks to overwrite the .create()
So, the weirdest thing that when I do this way of overwriting, I’m forced to create a category and the book. This relates to models?
– heitor_deep
When you create a nested relationship by default it is read-only, i.e., you don’t need to create a category every time you create a book, you just need to associate an existing category. See if you are passing the parameter (read_only=True), like the examples I left.
– NoobDeveloper
I just corrected the models, even using read_only was asked to register the category.
– heitor_deep
your solution just needs a small adjustment, I would use the
get_or_create
since I don’t always need to create aTrack
orAlbum
, for example I may want to add a track to an existing album or vice versa django documentation– Davi Wesley