如何在django rest框架模型中创建created_by字段?

时间:2016-06-06 10:32:44

标签: django python-2.7 django-models django-rest-framework django-serializer

我想在django rest框架模型中创建一个created_by字段。

它应该包含当前登录用户的user_id,它应该是我不需要在JSON格式的POST请求期间发送它,它应该从请求本身获取,我如何使用django rest framework serializer实现它。

models.py文件:

class Company(models.Model):
    """Company model for information about company."""

    created_by = models.ForeignKey(User, null= True, blank= True, on_delete=models.CASCADE)
    company_name = models.CharField(max_length=100)

serializers.py文件:

class CompanySerializer(serializers.ModelSerializer):
"""Serializer for companies."""

    class Meta:
        model = Company
        fields = ('id', 'created_by', 'company_name')

v1.py文件:

class CompanyList(APIView):
"""Get and post companies data."""

    def get(self, request, format=None):
        """Get companies data.."""
        companies = Company.objects.all()
        serialized_companies = CompanySerializer(companies, many=True)
        return Response(serialized_companies.data)

    def post(self, request, format=None):
        """Post companies data."""
        serializer = CompanySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

3 个答案:

答案 0 :(得分:4)

您可以使用serializers.CurrentUserDefault()作为created_byCompanySerializer字段的默认值,并将该字段设为read_only=True

请参阅文档here

答案 1 :(得分:3)

方法-1:使用CurrentUserDefault()选项

您可以将default字段中的created_by参数作为serializers.CurrentUserDefault()传递,这会将其值设置为当前用户。

class CompanySerializer(serializers.ModelSerializer):
"""Serializer for companies."""

    class Meta:
        model = Company
        fields = ('id', 'created_by', 'company_name')
        extra_kwargs = {'created_by': {'default': serializers.CurrentUserDefault()}}

方法-2:在user 中传递serializer.save()

您可以将字段created_by设置为read_only,然后将request.user传递给serializer.save()

<强> serializers.py

class CompanySerializer(serializers.ModelSerializer):
"""Serializer for companies."""

    class Meta:
        model = Company
        fields = ('id', 'created_by', 'company_name')
        extra_kwargs = {'created_by': {'read_only':True}}

<强> v1.py

class CompanyList(APIView):
"""Get and post companies data."""

    def post(self, request, format=None):
        """Post companies data."""
        serializer = CompanySerializer(data=request.data)
        if serializer.is_valid():
            serializer.save(created_by=request.user) # pass current user
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

答案 2 :(得分:0)

试试这个解决方案

models.py文件

class Student(models.Model):
    middel_name = models.CharField(max_length=100)
    user = models.OneToOneField(User)

这是我的序列化文件

class GetStudentUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id','username', 'email', 'first_name', 'last_name')

class GetStudentSerializer(serializers.ModelSerializer):
    user = GetStudentUserSerializer('user.username')
    class Meta:
        model = Student
        fields = ('id','middel_name','user')
        depth = 1

    def create(self, validated_data):
        print "hello"
        student_data = validated_data.pop('student', None)
        user = super(GetStudentSerializer, self).create(validated_data)
        self.create_or_update_student(user, student_data)
        return user

    def update(self, instance, validated_data):
        student_data = validated_data.pop('student', None)
        self.create_or_update_student(instance, student_data)
        return super(GetStudentSerializer, self).update(instance, student_data)

    def create_or_update_student(self, user, student_data):
        student, created = Student.objects.get_or_create(user=user, defaults=student_data)
        if not created and student_data is not None:
        super(GetStudentSerializer, self).update(instance, student_data)