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

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

概述我想在 django rest框架模型中创建一个created_by字段. 它应该包含当前登录用户的user_id,它应该是我不需要在JSON格式的POST请求期间发送它,它应该从请求本身获取,我如何使用django rest framework serializer实现它. models.py文件: class Company(models.Model): """Company mode 我想在 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,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)
解决方法 方法-1:使用 CurrentUserDefault()选项

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

class CompanySerializer(serializers.ModelSerializer):"""Serializer for companIEs."""    class Meta:        model = Company        fIElds = ('ID','company_name')        extra_kwargs = {'created_by': {'default': serializers.CurrentUserDefault()}}

方法2:在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','company_name')        extra_kwargs = {'created_by': {'read_only':True}}

v1.py

class CompanyList(APIVIEw):"""Get and post companIEs data."""    def post(self,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_400_BAD_REQUEST)
总结

以上是内存溢出为你收集整理的如何在django rest框架模型中创建created_by字段?全部内容,希望文章能够帮你解决如何在django rest框架模型中创建created_by字段?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1193663.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存