class One(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
one = models.CharField(max_length=20)
ses = models.IntegerField()
occupied = models.BooleanField(default=False)
我有occupied
个布尔字段,默认为False
。我想禁用各自的视图或仅在占据True
class OneSerializer(serializers.ModelSerializer):
class Meta:
model = One
field = '__all__'
read_only_fields = ('user',)
class OneView(APIView):
@staticmethod
def get(request):
user = request.user
apt = One.objects.filter(user=user)
if type(apt)==Response:
return apt
return Response(OneSerializer(apt).data)
@staticmethod
def post(request):
serializer = OneSerializer(data=request.data, context = {'request':request})
if serializer.is_valid():
user = request.user
serializer.save(user=user)
return Response(OneSerializer(serializer.instance).data, status=201)
return Response(serializer.errors, statusl=400)
我该如何使该功能设置为True,使各自的视图仅对所有者用户只读?
答案 0 :(得分:0)
尝试如下更改您的get()
方法
class OneView(APIView):
@staticmethod
def get(self, request, **kwargs):
user = request.user
apt = One.objects.get(user=user)
if apt.occupied:
return Response(OneSerializer(apt).data)
return Response()
如果您返回诸如类之类的HttpResponse以外的任何内容,则DRF将引发 AssertionError
作为
/ some / end / point /处的AssertionError预期响应,HttpResponse 或从视图返回HttpStreamingResponse,但收到一个
此外,我认为您的方法中不需要@staticmethod
。 DRF-Doc教会了我们在没有staticmethod
装饰器的情况下做到这一点。