我有两个模型Music
和MusicList
(manytomanyfield),我使用ViewSet生成api。我希望在我调用http://127.0.0.1:8000/api/musiclist/7/(GET)之类的电话时,它会返回Music的详细信息(包括music_name,music_id ...),这需要嵌套关系。
但是我也想用MusicList
更新music_id
,可以通过使用serializers.PrimaryKeyRelatedField
我试图定义两个字段以分别指定write_only和read_only,但我认为这不是一个好的解决方案。
models.py
class MusicList(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='user', related_name='musiclist')
name = models.CharField('list_name', max_length=50, default='')
music = models.ManyToManyField(Music)
def __str__(self):
return self.name
serializers.py
class MusicSerializer(serializers.ModelSerializer):
class Meta:
model = Music
fields = '__all__'
class MusicListSerializer(serializers.ModelSerializer):
# music = MusicSerializer(many=True, required=False)
music = serializers.PrimaryKeyRelatedField(many=True, queryset=Music.objects.all())
class Meta:
model = MusicList
fields = ['user', 'name', 'music']
validators = [
UniqueTogetherValidator(
queryset=MusicList.objects.all(),
fields=['user', 'name']
)
]