class Nugget(TimeStampedModel):
added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='added_by', blank=True, null=True)
class NuggetSerializer(TaggitSerializer, serializers.ModelSerializer):
added_by = serializers.CreateOnlyDefault(default=serializers.CurrentUserDefault())
class NuggetList(generics.ListCreateAPIView):
queryset = Nugget.objects.all()
serializer_class = NuggetSerializer
def perform_create(self, serializer):
serializer.save(added_by=self.request.user)
added_by
应该:
create
Nugget
user
的{{1}},无法覆盖此默认Nugget
时包含并显示Nugget
的选项
create/POST
答案 0 :(得分:3)
更改added_by
serializers.py
(不是使用字段,并设置为read_only)和.save()
中的views.py
以停止覆盖默认值。
CurrentUserDefault()
在request
字典中需要context
。在这种情况下,generics.ListCreateAPIView
已经这样做了。
class Nugget(TimeStampedModel):
added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='added_by', blank=True, null=True)
class NuggetSerializer(TaggitSerializer, serializers.ModelSerializer):
added_by = serializers.StringRelatedField(default=serializers.CurrentUserDefault(), read_only=True)
class NuggetList(generics.ListCreateAPIView):
queryset = Nugget.objects.all()
serializer_class = NuggetSerializer
def perform_create(self, serializer):
serializer.save()
答案 1 :(得分:1)
我是通过以下方式做到的(无需使该字段可为空):
models.py
class Nugget(models.Model):
added_by = models.ForeignKey(to=User, related_name='added_by', on_delete=models.DO_NOTHING)
serializers.py
class NuggetSerializer(serializers.ModelSerializer):
added_by = serializers.StringRelatedField(default=serializers.CurrentUserDefault(), read_only=True)
class Meta:
model = Nugget
fields = ['added_by']
views.py
class NuggetList(viewsets.ModelViewSet):
queryset = Nugget.objects.all()
serializer_class = NuggetSerializer
def perform_create(self, serializer):
request = serializer.context["request"]
serializer.save(added_by=request.user)
答案 2 :(得分:0)
我必须更新views.py
才能使其正常工作:
class NuggetList(generics.ListCreateAPIView):
queryset = Nugget.objects.all()
serializer_class = NuggetSerializer
permission_classes = (IsAuthenticated,)
def perform_create(self, serializer):
req = serializer.context['request']
serializer.save(added_by=req.user)