Skip to main content
 首页 » 编程设计

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

2024年11月24日9zfyouxi

我正在为我的网页创建一个自动完成搜索,我正在尝试使用 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可以在这里找到。