python - User 类型的对象不是 JSON 可序列化的

标签 python django django-models django-views

我正在为我的网页创建一个自动完成搜索,我正在尝试使用 ajax 调用从数据库中获取用户名。

我的 AJAX 调用运行良好并转到指定的 URL。

我试过使用 JSON 编码器,但也没有用。

我对 DJANGO 有点陌生,请帮忙

我的views.py

def autocomplete(request):
if request.is_ajax():
    q = request.GET.get('search', '').capitalize()
    search_qs = Profile.objects.filter(user__username__startswith=q)
    results = []
    print (q)
    for r in search_qs:
        results.append(r.user)
    data= json.dumps(list(results), cls=DjangoJSONEncoder)
else:
    data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)

我的models.py

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')

def __str__(self):
    return f'{self.user.username} Profile'

错误我得到

TypeError: Object of type User is not JSON serializable
[] "GET /ajax_calls/search/?**term=he** HTTP/1.1" 500 15860

最佳答案

我不知道你为什么要通过Profile查询,这里可以直接通过User查询。我认为正确的实现应该是这样的:

from django.core.serializers import serialize 

users = User.objects.filter(username__startswith=q)

str_data = serialize('json', users, cls=DjangoJSONEncoder). # Or you don't need to provide the `cls` here because by default cls is DjangoJSONEncoder

data = json.loads(str_data)

Documentation可以在这里找到。

关于python - User 类型的对象不是 JSON 可序列化的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55610620/

相关文章:

django 模型中的星期几表示

python - Django新手错误: - TypeError: view must be a callable or a list/tuple in the case of include()

python - 我如何让 pylint 识别 twisted 和 ephem 成员?

python - xlsxwriter 中的粗边框

python - 使用OpenCV连接USB摄像头

python - 使用 python/django 从字符串中删除非 ASCII 字符

python - 切换到 django-pytest 后,我​​还能使用 `manage.py test` 吗?

python - Pandas 将列分成多个

python - 在 django 测试中传递参数

python - django.db.utils.ProgrammingError : cannot cast type text[] to jsonb