gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:32:48 24 4
gpt4 key购买 nike

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

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

模型.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)

最佳答案

方法一:使用 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()}}

方法二:通过 userserializer.save()

您可以设置字段 created_byread_only然后通过 request.userserializer.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)

关于django - 如何在 django rest 框架模型中创建 created_by 字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37655184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com