【问题标题】:Django Copy multiple items from DB Query to dictDjango 将多个项目从 DB Query 复制到 dict
【发布时间】:2017-11-22 13:20:03
【问题描述】:

我对 Django 和 dicts 有疑问。我只想获得与以下内容匹配的项目。但我无法让它工作。感谢您的帮助。

django_db_query = [{'time': '13:00 Uhr', 'titel': 'test1'}, {'time': '14:00 blah', 'titel': 'test2'}, {'time': '13:00 Uhr', 'titel': 'test3'},]
all_db_items = Django_db.objects.all()

only_13 = dict()
for item in all_db_items:
    if item.time is "13":
        only_13 += item

想要:我的数据库中的数据结构和多个值在我的字典中,但仅限于 13:00 Uhr 的时间

for item in only_13:
    print item.titel

console
   test1
   test2

【问题讨论】:

  • 您能提供给我们您的模型定义吗?

标签: python django dictionary


【解决方案1】:

假设你的 DjangoDbModel 看起来像

def DjangoDbModel(models.Model):
    time = models.DateTimeField()
    title = models.CharField(max_length=256)

在这种情况下,您需要做的就是 DjangoDbModels.objects.filter(time__hour=13) 如果您只想拥有从 13 小时开始的项目。例如,您可以将类似的过滤器应用于日、年和月。

【讨论】:

  • 我已经尝试过这条路,但以后我只会有 > 比我当前时间的项目。我认为这不适用于数据库查询
  • 肯定会的!将您的 CharField 更改为 DateTimeField,您可以灵活地查询它:) range 应该很好,例如:docs.djangoproject.com/en/1.11/ref/models/querysets/#range
  • 我想我没有得到查询集和字典的定义,
  • 在我的代码中我将数据库查询加载到我的变量 all_db_item 稍后在我的代码中我创建 dict 上下文并在上下文中创建键 db,值为 all_db_items 这将进入我的模板,而 jinga 可以通过{% for item in db %} <li>{{ item.titel }}</li> `{% endfor %} 访问它,请解释一下我的字典如何可以容纳多个值。我的意思是为什么我可以对字典值进行交互?它是如何分开的?以及如何在自制字典中重建它? o.O
【解决方案2】:
for item in all_db_items:
    if item['time'] == "13:00 Uhr":
        only_13.update(item)

is 仅适用于 相同 操作数

+ 未针对字典实现,请改用update

更多资源: https://www.python-course.eu/dictionaries.php

【讨论】:

  • 你能举一个itemitem.time 的例子吗?
  • 根据您的模型定义更新了我的答案
猜你喜欢
  • 2017-12-16
  • 1970-01-01
  • 2021-06-26
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多