尝试将列表与 Django 中的 DateTimeField 和日期对象结合起来
我有 2 个带有 Title 和 Created_At DateTimeField (文章和项目)的 Django 查询列表,我还有另一个列表,它是返回字符串 Title 和 Create_At 日期对象的 python 函数的结果。
我想将这些列表链接在一起,以便可以将它们组合起来并按日期字段对结果进行排序 - 但是目前我收到以下错误:
can't compare datetime.datetime to tuple
如何将这两个列表放在一起?导致错误的代码是:
latest_changes = sorted(
chain(articles, projects, tweets),
key=lambda instance: instance.created)
OR是否有更好的方法来执行此操作而不是使用链?理想情况下,我想创建一个新列表,而不必使各个列表字段名称也匹配(我收集类似名称的链匹配项)。
I've got 2 Django query lists with a Title and a Created_At DateTimeField (Articles and Projects), I have another list which is the result of a python function that returns a string Title and a Create_At date object.
I want to chain these lists together so I can combine them and sort the results by their Date fields - however at the moment I'm getting the following error:
can't compare datetime.datetime to tuple
How do I get these two lists together? The code causing the error is:
latest_changes = sorted(
chain(articles, projects, tweets),
key=lambda instance: instance.created)
OR Is there a better way to do this instead of using chain? Ideally I'd like to create a new list without having to have the individual list field names matching as well (I gather chain matches like to like on names).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为 tweets.created 是一个元组而不是 Datetime 对象。您可以使用 dateutil 模块将元组转换为 python 中正确的 Datetime 对象,然后您可以无缝比较:)
I think the tweets.created is a tuple rather than a Datetime object. You can use the dateutil module to convert the tuple into a proper Datetime object in python and then you can compare seamlessly :)
从错误消息来看,显然
instance.created
是链式可迭代对象之一的元组。我的猜测是,它是您所讨论的“返回字符串 Title 和 Create_At 日期对象的 python 函数的结果”的项目,因为
DateTimeField
不会返回元组。type(tweets[0].created) == tuple
返回True
吗?Judging by the error message, apparently
instance.created
is a tuple for one of your chained iterables.My guess is that it's whichever item is the "result of a python function that returns a string Title and Create_At date object" that you were talking about, as a
DateTimeField
wouldn't return a tuple.Does
type(tweets[0].created) == tuple
returnTrue
?