我正在Django中编写REST API,我创建模型Member,其中ForeignKey来自用户表(auth_user)...方法GET工作完美,但与后我有问题...每次我看到错误消息,fk_id不能为空。
models.py
class Member(models.Model):
valid_from = models.DateTimeField(null=True, blank=True)
valid_to = models.DateTimeField(null=True, blank=True)
online = models.IntegerField()
vpn_ip = models.CharField(max_length=20, unique=True)
created = models.DateTimeField(auto_now_add=True)
fk = models.ForeignKey(User, on_delete=models.CASCADE)
@property
def username(self):
return self.fk.username
@property
def password(self):
return self.fk.password
@property
def email(self):
return self.fk.email
@property
def status(self):
return self.fk.is_active
@property
def admin(self):
return self.fk.is_staff
@property
def fk_id(self):
return self.fk.id
def __str__(self):
return self.username
views.py
class MemberData(APIView):
serializer_class = MemberDataSerializer
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
'''
Retrieves all Member from database
'''
data = Member.objects.all()
serializer = MemberDataSerializer(data, many=True)
return Response(serializer.data)
def post(self, request, *args, **kwargs):
'''
Put new member to database
'''
data = {
"fk_id": request.data.get('fk_id'),
"valid_from": request.data.get('valid_from'),
"valid_to": request.data.get('valid_to'),
"online": request.data.get('online'),
"vpn_ip": request.data.get('vpn_ip'),
}
serializer = MemberDataSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
class MemberDataSerializer(serializers.ModelSerializer):
class Meta:
model = Member
fields = ["id", "fk_id", "username", "password", "email", "status", "admin", "valid_from", "valid_to", "online", "vpn_ip", "created"]
如果我尝试将数据发布为 application/json,则会看到此错误...
像这样的 Postman 发送数据..
{
"fk_id": 1,
"valid_from": null,
"valid_to": null,
"online": 0,
"vpn_ip": "10.40.10.3"
}
异常类型:完整性错误
异常值:(1048,“列'fk_id'不能为空”)
1条答案
按热度按时间iih3973s1#
我自己解决的。很简单...