我有一个用户模型和一个音乐会模型。音乐会模型对用户模型具有m2m字段。在Concert视图中,我想要一个与Concert模型有关的用户字典列表。这是我得到的:

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中的technicals-fields是包含用户名称,电子邮件和ID的词典列表。为什么它不提供DRF Documentation on Nested Serializers所说的那样呢?

最佳答案

为什么添加source,您使用与模型字段相同的序列化器字段,只需将其删除即可。

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

关于python - DRF3在m2m关系上创建嵌套的序列化器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46561844/

10-12 04:32