Django休息 - 序列化相关对象

时间:2017-02-18 18:12:26

标签: python django serialization django-models django-rest-framework

我正在使用Django 1.10.5django rest framework 3.5.3。 我创建了一个名为Abstract的模型,它有一个相关的字段User和一个Minisymposium

当我发布新的Abstract时,我会输入用户和minisymposium的ID。 但是我不想在获取对象时获取ID,我想获取序列化对象(例如:我发布用户' 2'并获取用户:{name: david, id: 2}

我该怎么办?

class Abstract(models.Model):
    STATUS_CHOICES = (
        ('submitted', 'Submitted'),
        ('mso_approved', 'MSO Approved'),
        ('congress_org_approved', 'Congress Org Approved'),
        ('approval_email_sent', 'Approval email sent'),
        ('scheduled', 'scheduled'),
        ('denied', 'Denied')
    )
DISPLAY_STATUS_CHOICES = (
    ('pending', 'Pending'),
    ('approved', 'Approved'),
    ('scheduled', 'scheduled'),
    ('denied', 'Denied')
)

id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100, null=False)
description = models.TextField(max_length=9000, null=False)
minisymposium = models.ForeignKey(Minisymposium, related_name='abstracts', null=False)
status = models.CharField(max_length=100, choices=STATUS_CHOICES, null=False, default='submitted')
display_status = models.CharField(max_length=100, choices=DISPLAY_STATUS_CHOICES, null=False, default='pending')
user = models.ForeignKey(User, null=False)
date = models.DateTimeField(auto_now_add=True)

def __str__(self):
    return str(self.id) + ' ' + self.title


class AbstractSerializer(serializers.ModelSerializer):
    authors = AuthorSerializer(many=True, read_only=True)
    minisymposium = MinisymposiumSerializer(read_only=True)

class AbstractViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Abstract.objects.all()
    serializer_class = AbstractSerializer
    filter_fields = ['id', 'title', 'description', 'status', 'minisymposium',
                     'display_status', 'date', 'user']
    search_fields = ['id', 'title', 'description', 'status', 'display_status', 'minisymposium__title',
                     'user__username', 'user__first_name', 'user__last_name']
    ordering_fields = ['id', 'title', 'description', 'status', 'display_status', 'minisymposium__number',
                       'minisymposium__title',
                       'date', 'user__first_name']

    def create(self, request, *args, **kwargs):
        request.data['user'] = request.user.id
        return super(AbstractViewSet, self).create(request, *args, **kwargs)

        class Meta:
            model = Abstract
            fields = ('id', 'date', 'title', 'description', 'status', 'display_status',
                      'url', 'user', 'minisymposium', 'authors')

0 个答案:

没有答案