Django Rest Framework:发布对象时如何将对象与用户关联

时间:2019-02-28 08:34:47

标签: django django-rest-framework

我是创建REST API的新手,所以我可能会误解。 我正在使用Django Rest Framework创建REST API。而且我正在尝试创建一个对象并通过移动应用发送该对象。

但是,API返回400。我认为它仍然无法将对象与请求用户相关联,我想知道如何实现。

models.py

class Item(models.Model):
    item_name = models.CharField()
    created_at = models.DateTimeField(auto_now_add=True)
    created_by = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

serializers.py

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('item_name', 'created_by')

views.py

class ListItems(generics.ListCreateAPIView):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer

我想知道的是像我们一样在发布对象时如何将对象与请求用户相关联

if form.is_valid():
    item = form.save(commit=False)
    item.created_by = request.user
    item.save()        

4 个答案:

答案 0 :(得分:2)

我认为最简单的方法是这样的:

class ItemSerializer(serializers.ModelSerializer):

 created_by = serializers.HiddenField(
    default=serializers.CurrentUserDefault()
)

可以找到参考文献here

答案 1 :(得分:1)

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('item_name',)

class ListItems(generics.ListCreateAPIView):
    ...
    def perform_create(self, serializer):
        serializer.save(created_by=self.request.user)

您可以这样做

答案 2 :(得分:1)

覆盖serializer_create方法的一种可能方法。由于user首先没有与request.data关联,因此我们需要确保这是write_only字段,并且还需要从modelSerializer的self.context.request.user分配当前用户。接下来的添加应该可以解决问题。

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('item_name', 'created_by')
        extra_kwargs = {'created_by': {'write_only': True}}

    def create(self, validated_data):
        item = Item(
            item_name=validated_data['item_name'],
            created_by=self.context.request.user
        )

        item.save()
        return item

引用link

答案 3 :(得分:0)

对我有用

models.py

class Category(models.Model):
   name = models.CharField('Category', max_length=200, unique=True, help_text='Name of the category')
   slug = models.SlugField('Slug', max_length=100, db_index=True, unique=True, help_text='Name of the category in format URL')

   def __str__(self):
       return (self.name)

   def save(self, *args, **kwargs):
       self.slug = slugify(self.name)     
       super(Category, self).save(*args, **kwargs)    

serializers.py

 class CategorySerializer(serializers.ModelSerializer):
   class Meta:
       model = Category
       fields = [
           'id', 'name', 'slug'
       ]
       read_only_fields = [
          'slug', 
       ]

最后,在保存帖子之前,将用户吸引到了视图中。

views.py

class CategoryList(APIView):te a new category instance.

   permission_classes = (IsAuthenticatedOrReadOnly,)

   def get(self, request, format=None):
       categories = Category.objects.all()
       serializer = CategorySerializer(categories, many=True)
       return Response(serializer.data, status=status.HTTP_200_OK)

   def post(self, request, format=None):
       serializer = CategorySerializer(data=request.data)
       if serializer.is_valid():
           serializer.save(created_by=self.request.user)
           Response(serializer.data, status=status.HTTP_200_OK)
       return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)