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

How to create a created_by field in django rest framework model?

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

它应该包含,user_id 当前登录的用户,它应该是这样的,我不需要在 POST 请求期间以 JSON 格式发送它,它应该取自请求本身,我如何使用 django rest 框架序列化程序实现它。

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)

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

查看文档 here

试试这个解决方案

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)

方法一:使用CurrentUserDefault()选项

您可以在 created_by 字段中将 default 参数作为 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()}}

方法二:在serializer.save()

中传递user

您可以将字段 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)