django在序列化器中从多到多字段中仅选择特定字段

时间:2019-02-21 05:12:45

标签: django python-3.x django-rest-framework

我的模特:

class RequisiteItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    enrollable = models.ForeignKey(Enrollable, on_delete=models.CASCADE)
    created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE)
    completed_within_days = models.IntegerField()
    date_completed_by = models.DateTimeField(default=now, editable=False)

class Requisite(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name =  models.CharField(default=None, blank=True, null=True, max_length=255)
    description = models.CharField(default=None, blank=True, null=True, max_length=255)
    items = models.ManyToManyField(RequisiteItem, blank=True)
    enrolments = models.ManyToManyField(Enrollee, blank=True)
    created_by = models.ForeignKey(ElsUser, on_delete=models.CASCADE, related_name="requisites", default=None)
    timestamp = models.DateTimeField(default=now, editable=False)

    @property
    def created_by_user(self):
        return self.created_by.username

序列化器类:

class RequisiteSerializer(serializers.ModelSerializer):
    created_by = serializers.CharField(source='created_by_user')

    class Meta:
        model = Requisite
        fields = ('id', 'name', 'description', 'items', 'enrolments', 'created_by', 'timestamp')
        read_only_fields = ['id']
        depth = 1

我有由必需项创建的注册,这些必需项是外键和许多字段等。在我的列表API中,我只希望显示外键中的特定文件。例如,在created by字段中,Elsuser是从AbstractUser继承的自定义用户。我只需要此模型的用户名和电子邮件字段,而不需要整个字段。许多领域的类似情况。我该如何执行呢?

1 个答案:

答案 0 :(得分:0)

您可以创建一个序列化器以仅获取必填字段。示例:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('') #the fields you require to display

然后将您的序列化器更改为:

class RequisiteSerializer(serializers.ModelSerializer):
    created_by = UserSerializer()

    class Meta:
        model = Requisite
        fields = ('id', 'name', 'description', 'items', 'enrolments', 'created_by', 'timestamp')
        read_only_fields = ['id']
        depth = 1