Django -User类型的对象不能进行JSON序列化

mi7gmzs6  于 2023-01-27  发布在  Go
关注(0)|答案(1)|浏览(126)

将数据(具有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中。

zhte4eai

zhte4eai1#

您的user可能是Django用户模型示例,它是JSON不可序列化的:

data_params = {
        "log_user_id": user, # <-- here
data=json.dumps(data_params) # <-- here

您应该将user.pk放入data_params中:

data_params = {
        "log_user_id": user.pk, # <-- here

相关问题