gpt4 book ai didi

django - 如何在 django JSON 中将用户 ID 替换为用户名?

转载 作者:行者123 更新时间:2023-12-04 05:59:55 30 4
gpt4 key购买 nike

我正在用 ajax 写一个简单的聊天,我有一个 JSON 问题。我需要username而不是 id .

JSON 看起来像:

[{"pk": 41, "model": "chat.post", "fields": {"timestamp": "2012-01-27 22:14:46", "user": 1, "text": "weq"}}]`

我需要更换 "user": 1"user": username .

我该怎么做?

我的型号:
    from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
text = models.TextField()
user = models.ForeignKey(User)

class Meta:
ordering = ['-id']

def __unicode__(self):
return "[%s] %s by user: %s" % (
self.timestamp.strftime("%Y-%m-%d %H:%M:%S"),
self.text,
self.user
)

我的观点:
# -*- coding: utf-8 -*-
#!/usr/bin/env python
from django.http import HttpResponse
from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
from django.shortcuts import render_to_response

from live.chat.models import Post

@login_required
def updates_after(request, id):
response = HttpResponse()
response['Content-Type'] = "text/javascript"
response.write(serializers.serialize("json",
Post.objects.filter(pk__gt=id)))
# __gt - greaten then > id
return response

@login_required
def saymessage(request):
if request.method == 'POST':
if "text" in request.POST:
text = request.POST["text"]
user = request.user
message = Post()
message.user, message.text = user, text
message.save()
return HttpResponseRedirect('/')
else:
pass

JSON 响应示例:
[
{
“PK”:42,
"model": "chat.post",
“领域”:{
"时间戳": "2012-01-28 18:08:44",
“用户”:1,
"text": "dasd"
}
}
]

我的模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />

<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame
Remove this if you use the .htaccess -->
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />

<title>templates</title>
<meta name="description" content="" />
<script type="text/javascript" language="javascript" src="/media/js/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function update() {
update_holder = $("#update_holder");
most_recent = update_holder.find("div:first");
$.getJSON("/live/updates-after/" + most_recent.attr('id') + "/",
function(data) {
cycle_class = most_recent.hasClass("odd") ? "even" : "odd";
jQuery.each(data, function(){
update_holder.prepend('<div id="' + this.pk
+ '" class="update ' + cycle_class
+ '"><div class="timestamp">'
+ this.fields.timestamp
+ '</div><div class="user">'
+ this.fields.user
+ '</div><div class="text">'
+ this.fields.text
+ '</div><div class="clear"></div></div>'
);
cycle_class = (cycle_class == "odd") ? "even" : "odd";
});
}

);
}
$(document).ready(function() {
setInterval("update()", 10000);
})
</script>
<link rel="stylesheet" type="text/css" href="/media/css/main.css" />
</head>
<body>
{% block content %}
<div>
<header>
<h1>Live Update site</h1>
<p>Содержимое обновляется автоматически</p>
</header>
{% if object_list %}
<div id="update_holder">
{% for object in object_list %}
<div class="update {% cycle even,odd %}" id="{{ object.id }}">
<div class="timestamp">
{{ object.timestamp|date:"Y-m-d H:i:s" }}
</div>
<div class="user">
{{ object.user }}
</div>
<div class="text">
{{ object.text|linebreaksbr }}
</div>
<div class="clear"></div>
</div>
{% endfor %}
</div>
{% else %}
<p>Нет обновлений</p>
{% endif %}
</div>
<form enctype="multipart/form-data" action="{% url chat.views.saymessage %}" method="post">{% csrf_token %}
Введите текст сообщения: <input type="text" name="text" id="text">
<input type="submit" name="submit" value="Отправить">
</form>
{% endblock %}
</body>
</html>

更新:
我弄明白了这个问题,我们需要使用natural_key(),并在用户管理器类中重写这个方法,在models.py中添加下一段代码:
class UserManager(models.Manager):
def unatural_key(self):
return self.username
User.natural_key = unatural_key

并且不要忘记添加参数 use_natural_keys=True到 serializers.serialize()

最佳答案

您可能想查看 Natural Keys .自然键允许您指定序列化为哪些外键字段。通过为您的用户构建主键,您可以在序列化中使用用户名,而不是 ID。

关于django - 如何在 django JSON 中将用户 ID 替换为用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9046284/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com