DRF3在m2m-relation上创建嵌套序列化程序

时间:2017-10-04 09:48:57

标签: python django django-rest-framework

我有一个用户模型和一个Concert模型。 Concert模型具有用户模型的m2m字段。在Concert-views中,我想要一个与Concert-model相关的User的词典列表。这就是我得到的:

models.py

class User(AbstractBaseUser, PermissionsMixin):
    objects = UserManager()
    name = models.CharField(max_length = 255, default = "")
    date_added = models.DateField(auto_now=False, auto_now_add=True)
    email = models.EmailField(unique=True, db_index=True)
    (more but irrelevant)

class Concert(models.Model):
    name = models.CharField(max_length = 255)
    technicians = models.ManyToManyField(User)

serializers.py

class ConcertListSerializer(serializers.ModelSerializer):
    technicians = UserDetailSerializer(
            many=True,
            read_only=True,
            source='concert_set'
        )

    class Meta:
        model = models.Concert
        fields = [
            'name',
            'technicians',
            'id',
        ]

class UserDetailSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = [
            'name',
            'email',
            'id',
        ]

我期望ConcertListSerializer中的technicians-field是一个包含用户名,电子邮件和id的字典列表。为什么不像DRF Documentation on Nested Serializers所说的那样提供这个呢?

1 个答案:

答案 0 :(得分:3)

为什么添加source使用与模型字段相同的序列化程序字段,只需删除它。

class ConcertListSerializer(serializers.ModelSerializer):
    technicians = UserDetailSerializer(
            many=True,
            read_only=True,
        )