Django model序列化json

model类
class UserInfo(models.Model):
    user_name = models.CharField(max_length=32, default="")
    user_pwd = models.CharField(max_length=32, default="")
    phone_number = models.CharField(max_length=32, default="")
    phone_verify = models.BooleanField(default=False)
    create_time = models.DateTimeField(default=timezone.now)
    update_time = models.DateTimeField(auto_now=True)
QuerySet序列化返回json
# user = models.UserInfo.objects.filter(phone_number=phonenumber)
all_data = models.UserInfo.objects.values('id', 'user_name', 'phone_number', 'phone_verify', 'create_time')
all_data = list(all_data)
return JsonResponse(all_data, safe=False)
# safe=Ture如果返回类型不是字典会抛出异常

还有一个好用的三方库
https://github.com/bluedazzle/django-simple-serializer
但是在DateField存在一个问题 'AutoField' object has no attribute 'rel'

这位兄弟提供了一个解决办法
初步解决 'AutoField' object has no attribute 'rel' 问题
https://github.com/bluedazzle/django-simple-serializer/issues/8

你可能感兴趣的:(Django model序列化json)