如何使用PrimaryKeyRelatedField在ModelSerializer中将owner重命名为owner_id?

时间:2018-09-11 00:40:32

标签: django django-rest-framework

我想将我的owner字段重命名为owner_id,因为它不是嵌套的,只包含所有者的ID。我做了一些尝试,但收到诸如{"owner":["This field is required."]}之类的错误。

这是我的serializers.py:

class UserJobApplicantSerializer(serializers.ModelSerializer):
    job_id = serializers.PrimaryKeyRelatedField(source='job', queryset=Job.objects.all())
    owner_id = serializers.PrimaryKeyRelatedField(
        source='owner',
        read_only=True,
        default=serializers.CurrentUserDefault()
    )

    class Meta:
        model = JobApplicant
        fields = [
            'id',
            'job_id',
            'owner_id',
            'timestamp',
        ]
        read_only_fields = ['id',]

该视图将覆盖perform_create并将owner_id注入validated_data中:

class UserJobApplicantAPIView(generics.ListCreateAPIView):
    lookup_field = 'pk'
    serializer_class = UserJobApplicantSerializer
    permission_classes = (IsAuthenticated,)

    def get_queryset(self):
        return JobApplicant.objects.filter(owner=self.request.user)

    def perform_create(self, serializer):
        serializer.validated_data['owner_id'] = self.request.user.id
        return super(UserJobApplicantAPIView, self).perform_create(serializer)

模型(Job模型通过through ='JobApplicant'持有ManyToManyField):

class JobApplicant(models.Model):   
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,
            on_delete=models.CASCADE)
    job = models.ForeignKey(Job, on_delete=models.CASCADE)
    timestamp = models.DateTimeField(auto_now_add=True)                                                                                      

    class Meta:
        unique_together = ('owner', 'job')                                                                                               

    def __str__(self):
        return "{}: {}".format(self.job.display_name, self.owner.email)  

执行此操作的正确方法是什么?是否可以使用PrimaryKeyRelatedField,还是我需要使用其他类型的字段(或自定义)?我让它适用于job_id,但是job_id有所不同,因为它是由用户提供的。

我在Django 1.11.15上使用DRF 3.8.2。

1 个答案:

答案 0 :(得分:2)

read_only=True, 中删除 PrimaryKeyRelatedField 参数解决了 main 问题: )
应该是

from django.contrib.auth.models import User  # use the AUTH_USER_MODEL here

owner_id = serializers.PrimaryKeyRelatedField(source='owner', queryset=User.objects.all(), default=serializers.CurrentUserDefault())


注意:您不想覆盖 perform_create() 方法,以将用户实例传递给序列化程序。如果您已正确登录, CurrentUserDefault() 类将管理这些事情