将数据(具有User对象)发布到ModelViewSet时遇到问题。错误:“用户类型的对象不可JSON序列化”
data_params = {
"log_user_id": user,
"device_name": "sampledevice",
"log_user_email": "svc.netadc@ads.aexp.com",
"feature_name": 'Subnet Automation',
}
print(data_params, "data_params")
response = requests.post("<url>/netadc3/arista/ImplementationLogsAristaViewSet/implementationlogsarista/",
auth=(<username>, <password>), headers={"content-type": "application/json"}, data=json.dumps(data_params), verify=False)
serializers.py:
class ImplementationLogsAristaSerializer(serializers.HyperlinkedModelSerializer):
log_user_id = UserSerializer(read_only=True)
class Meta:
model = ImplementationLogsArista
fields = ('log_id','device_name', 'log_user_id','log_user_email','feature_name')
views.py:
class ImplementationLogsAristaViewSet(viewsets.ModelViewSet):
queryset = ImplementationLogsArista.objects.all()
serializer_class = ImplementationLogsAristaSerializer
permission_classes = (IsAuthenticated,)
pagination_class = None
models.py:
class ImplementationLogsArista(models.Model):
log_id = models.AutoField(primary_key=True)
device_name = models.CharField(max_length=800, verbose_name='Device Name',default='sampledevice')
log_user_id = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, verbose_name='User ID')
log_user_email = models.CharField(max_length=500, verbose_name='User Email',default='admin')
feature_name = models.CharField(max_length=100, verbose_name='Feature Name',default='default_feature')
class Meta:
verbose_name = 'Implementation/Backout Logs'
verbose_name_plural = 'Implementation/Backout Logs'
def __unicode__(self):
return '%s %s %s %s %s' % (self.log_id,self.device_name,self.log_user_id,self.log_user_email,self.feature_name)
不确定如何成功地将用户数据POST到ModelViewSet中。
1条答案
按热度按时间zhte4eai1#
您的
user
可能是Django用户模型示例,它是JSON不可序列化的:您应该将
user.pk
放入data_params
中: