使用django-rest-framework自动“由用户创建”字段?

时间:2016-07-24 20:02:37

标签: python django django-models django-rest-framework

models.py

class Nugget(TimeStampedModel):
    added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='added_by', blank=True, null=True)

serializers.py

class NuggetSerializer(TaggitSerializer, serializers.ModelSerializer):
    added_by = serializers.CreateOnlyDefault(default=serializers.CurrentUserDefault())

views.py

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应该:

  1. 设置为create
  2. Nugget
  3. 默认为创建user的{​​{1}},无法覆盖此默认
  4. 在检索到Nugget时包含并显示
  5. 未在可浏览API
  6. 中显示为Nugget的选项
  7. create/POST
  8. 后无法修改

3 个答案:

答案 0 :(得分:3)

更改added_by serializers.py(不是使用字段,并设置为read_only)和.save()中的views.py以停止覆盖默认值。

CurrentUserDefault()request字典中需要context。在这种情况下,generics.ListCreateAPIView已经这样做了。

models.py

class Nugget(TimeStampedModel):
    added_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, related_name='added_by', blank=True, null=True)

serializers.py

class NuggetSerializer(TaggitSerializer, serializers.ModelSerializer):
        added_by = serializers.StringRelatedField(default=serializers.CurrentUserDefault(), read_only=True)

views.py

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)