通过嵌套关系返回manytomany字段,并通过id更新

时间:2019-08-05 13:27:32

标签: django django-rest-framework

我有两个模型MusicMusicList(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']
            )
        ]

0 个答案:

没有答案