您好,我想知道根据 Django Rest Framework 中的请求与用户创建新模型条目的最佳实践是什么?
型号:
class Asset(models.Model):
user = models.ForeignKey(UserAccount, on_delete=models.CASCADE, related_name="assets")
name = models.CharField(max_length=200)
amount = models.DecimalField(max_digits=10, decimal_places=2)
序列化器:
class AssetSerializer(serializers.ModelSerializer):
class Meta:
model = Asset
fields = '__all__'
观点
class CreateAssetView(generics.CreateAPIView):
serializer_class = AssetSerializer
<Doesn't seem to work, possibly since user isn't in the json>
def perform_create(self, serializer):
serializer.save(user=self.request.user)
基本上,我希望能够向此端点发送 POST 请求
{name: 'myasset', amount: '50'}
,并使用从请求中获取的用户字段保存新的资产。最好的方法是什么?谢谢
*** 编辑 *** 想到更好的解决方案:
class CreateAssetView(generics.CreateAPIView):
serializer_class = AssetSerializer
queryset = Asset.objects.all()
def perform_create(self, serializer):
serializer.save(user=self.request.user)
但是这意味着我必须在前端的 POST 请求中发送一个虚拟的 user_id 。我不确定如何避免这种情况。非常欢迎任何建议。
由于帖子“作者”不能为空,那么我们需要提供一个用户, 一种方法是将用户实例放入前端的 request.data 中...... 下面的例子是在发出请求后将用户实例分配给后端的request.data!
...models.py
class Post(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
content = models.CharField(max_length=255)
...views.py
class PostCreate(CreateAPIView):
queryset = Post
serializer_class = PostSerializer
# override this method
def create(self, request, *args, **kwargs):
request.data['author'] = request.user.pk
return super().create(request, *args, **kwargs)
我最常使用基于函数的视图而不是基于类的视图来做这件事。 : 基本上,这还可以发送
POST
请求,并保存请求发布请求的用户。
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework.permissions import IsAuthenticated
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def perform_create(request, pk):
user = request.user
asset= Asset.objects.get(id=pk)
data = request.data
# Create Asset
asset = Asset.objects.create(
user=user,
name=user.first_name,
amount=data['amount '],
)
asset.save()
return Response('Asset Added')
为了返回数据,我为序列化数据创建另一个视图 在需要的地方。我想肯定还有其他方法,但是 这个非常简单易做。
@api_view(["POST"]) @permission_classes([已验证]) def create_post(请求): 尝试: 用户=请求.用户 request.data["用户"] = 用户.id 标题 = request.data.get("标题",无) 描述 = request.data.get("描述",无)
if not title or not description:
raise Exception("Please enter value for title and description")
serializer = PostSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"message": "Post created successfully", "data": serializer.data}, status=status.HTTP_201_CREATED)
except Exception as e:
return Response({"message" : str(e) },status=400)