问题
I want output like this. I have a task to complete more than 5 models with nested type and all CRUD methods by using RestFawork.If anyone knows the answer share with me.
{
"id": 1,
"first_name": "John 1",
"last_name": "Robert 1",
"instrument": "KeyBoard",
"album_musician": [
{
"id": 3,
"artist": 1,
"name": "Test robert",
"release_date": "2020-09-16",
"num_stars": 400
"Language": [
{
"Original": "English",
"Dubbed": "Tamil"
}
]
}
]
}
In this Code, I did only Sigle Nested Framework. My model.py
Serializer.py In this Serialization, I used the CRUD method
class AlbumSerializer(serializers.ModelSerializer):
class Meta:
model = Album
fields = ('id', 'artist', 'name', 'release_date', 'num_stars')
class MusicianSerializer(serializers.ModelSerializer):
album_musician = AlbumSerializer(many=True)
class Meta:
model = Musician
fields = ('id', 'first_name', 'last_name', 'instrument', 'album_musician')
lookup_field=id
def create(self, validated_data):
albums_data = validated_data.pop('album_musician')
musician = Musician.objects.create(**validated_data)
for album_data in albums_data:
Album.objects.create(artist=musician, **album_data)
return musician
def update(self, instance, validated_data):
albums_data = validated_data.pop('album_musician')
albums = (instance.album_musician).all()
albums = list(albums)
instance.first_name = validated_data.get('first_name', instance.first_name)
instance.last_name = validated_data.get('last_name', instance.last_name)
instance.instrument = validated_data.get('instrument', instance.instrument)
instance.save()
for album_data in albums_data:
album = albums.pop(0)
album.name = album_data.get('name', album.name)
album.release_date = album_data.get('release_date', album.release_date)
album.num_stars = album_data.get('num_stars', album.num_stars)
album.save()
return instance
来源:https://stackoverflow.com/questions/64008694/multi-nested-with-django-restframework-and-mongodb