将 ForeignKey 设置为当前登录的用户 | Django Rest 框架 ViewSets
Setting a ForeignKey to the current logged in user | Django Rest framework ViewSets
我正在使用 Django Rest Framework 的 ViewSets 构建 REST API,但遇到了一个问题。在我的 API 上使用 POST
请求时,我无法轻松地将当前登录的用户插入到模型中。
我正在连载的模型如下:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Question(models.Model):
op = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
time_created = models.DateTimeField(auto_now_add=True)
给我这个问题的字段是 op
字段,它是 Django 默认的外键 User
class.
这个 API 有一个 POST
URL 用于在网站上创建一个新问题。我希望视图集将 当前 登录用户插入到创建中。其他问题建议在序列化程序上定义自定义 create()
方法,但这不起作用,因为我想插入当前登录的用户,而不是一组用户。
我的序列化程序:
class QuestionSerializer(ModelSerializer):
class Meta:
model = Question
fields = ("op", "title", "body")
我的观点:
class QuestionViewSet(
mixins.UpdateModelMixin,
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
GenericViewSet,
):
queryset = Question.objects.all()
serializer_class = QuestionSerializer
添加到您的序列化程序以使用请求用户:
class QuestionSerializer(ModelSerializer):
op = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = Question
fields = ("op", "title", "body")
我正在使用 Django Rest Framework 的 ViewSets 构建 REST API,但遇到了一个问题。在我的 API 上使用 POST
请求时,我无法轻松地将当前登录的用户插入到模型中。
我正在连载的模型如下:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Question(models.Model):
op = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
time_created = models.DateTimeField(auto_now_add=True)
给我这个问题的字段是 op
字段,它是 Django 默认的外键 User
class.
这个 API 有一个 POST
URL 用于在网站上创建一个新问题。我希望视图集将 当前 登录用户插入到创建中。其他问题建议在序列化程序上定义自定义 create()
方法,但这不起作用,因为我想插入当前登录的用户,而不是一组用户。
我的序列化程序:
class QuestionSerializer(ModelSerializer):
class Meta:
model = Question
fields = ("op", "title", "body")
我的观点:
class QuestionViewSet(
mixins.UpdateModelMixin,
mixins.CreateModelMixin,
mixins.ListModelMixin,
mixins.RetrieveModelMixin,
GenericViewSet,
):
queryset = Question.objects.all()
serializer_class = QuestionSerializer
添加到您的序列化程序以使用请求用户:
class QuestionSerializer(ModelSerializer):
op = serializers.HiddenField(default=serializers.CurrentUserDefault())
class Meta:
model = Question
fields = ("op", "title", "body")