如何解决无法将关键字“ last_activity”解析为字段
正如标题所述,我正在尝试使用django order_by方法对帖子列表进行排序,由于后来将我使用的字段添加到列表中(该字段未在模型内部创建),所以失败了。
除了将字段添加到模型中之外,我真的可以做些什么吗?
这是型号代码
class post(models.Model):
title = models.CharField(max_length=236)
content = models.TextField()
post_board = models.ForeignKey(board,on_delete=models.CASCADE)
author = models.ForeignKey(User,on_delete=models.CASCADE)
release_date = models.DateField(auto_now_add=True)
views = models.IntegerField(default=0)
def __str__(self):
return self.title
添加额外字段的函数:
def forumdisplay(request,boardslug=None):
context = { 'board': None }
if boardslug:
context['board'] = board.objects.all().filter(slug=boardslug).first()
if context['board']:
context['posts'] = post.objects.all().filter(post_board=context['board'])
for eachpost in context['posts']:
eachpost.reply_count = len(reply.objects.all().filter(reply_to=eachpost))
eachpost.last_activity = eachpost.release_date
if eachpost.reply_count:
eachpost.last_activity = reply.objects.all().filter(reply_to=eachpost).order_by('release_date').first().release_date
context['posts'] = context['posts'].order_by('last_activity')
alter_posts(context['posts'])
else:
pass
return render(request,"board/forumdisplay.html",context)
我得到的错误:
Request Method: GET
Request URL: http://127.0.0.1:8000/forumdisplay/news/
Django Version: 3.0.4
Exception Type: FieldError
Exception Value:
Cannot resolve keyword 'last_activity' into field. Choices are: author,author_id,content,id,post_board,post_board_id,release_date,reply,title,views```
解决方法
你不能。
您尝试使用的 order_by 实际上会转换为要在数据库上执行的SQL命令,而数据库中没有名为 last_activity 的列,因此您无法应用此功能功能。
将新列添加到数据库并使其可空是什么问题?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。