简体   繁体   English

在Django中将对象存储到字典中

[英]Storing objects into dictionary in Django

In my database I have stored some of my errors so I can easily send them between views. 我在数据库中存储了一些错误,因此可以轻松地在视图之间发送它们。 Here's a my models.py: 这是我的models.py:

class Errors(models.Model):
    error_number = models.IntegerField(primary_key=True)
    error_message = models.CharField(max_length=45)
    status = models.BooleanField(default=0)
    datetime = models.DateTimeField(auto_now=True)

I want to put errors into a dictionary so I can pass it to template after. 我想将错误放入字典中,以便以后将其传递给模板。 I want this to happen only if status is True / 1. Is the view bellow the correct approach to do this? 我希望仅当状态为True / 1时才发生这种情况。视图是否是执行此操作的正确方法?

As it is now I think it's a bad program, since I'm flooding newtwork while calling Errors.objects.all(), but I do not know otherwise how to implement the for loop. 现在,由于我在调用Errors.objects.all()时泛滥了newtwork,因此我认为这是一个不好的程序,但是我不知道如何实现for循环。

def index(request):
    err = {'error_numbers':[], 'error_messages': [], 'datetime':[], 'test':[]}

    warnings = Errors.objects.all()

    for warning in warnings:
        if Errors.objects.filter(status='1'):
            err['error_numbers'].append(warning.error_number)
            err['error_messages'].append(warning.error_message)
            err['datetime'].append(warning.datetime)

    return render(request, "index.html", err)

May I also ask how could I group all data of same error ie error number, error message and datetime in template to be displayed together? 我还可以问如何将相同错误的所有数据(即错误号,错误消息和日期时间)分组到模板中以一起显示吗? (PS I do realise that asking for code in SO is a no-no thus is only optional to anyone who is willing to share some useful site, or example). (PS我确实意识到,以SO要求代码是不行的,因此,这对于愿意共享一些有用站点或示例的任何人来说都是可选的)。

Example (as I use at the moemnt) bellow does not print anything at all. 下面的示例(正如我在moemnt上所使用的)完全不打印任何内容。

<ul>
{% for key, value in err.iteritems %}
     <li>{{key}: {{value}}</li>
{% endfor %}
</ul>

There is a lot to say about the code you have shared. 关于您共享的代码,有很多话要说。

First of all, I am not really sure why you really need a dictionary with this structure. 首先,我不太确定为什么您真的需要具有这种结构的字典。 What is your desired output? 您想要的输出是什么?


Secondly, this code piece is fishy: 其次,这段代码很烂:

for warning in warnings:
    if Errors.objects.filter(status='1'):
        ....

status is a BooleanField . status是一个BooleanField You should filter it by a boolean value. 您应该使用布尔值对其进行过滤。 On the other hand, why do you need to filter out the whole database in an iteration? 另一方面,为什么需要迭代过滤掉整个数据库? Did you mean something like this? 你的意思是这样吗?

for warning in warnings:
    if warning.status:
        ...

Another thing is the naming you chose. 另一件事是您选择的命名。 It is a better practice to give your models singular names. 最好给模型起一个单数的名字。 Use Error instead of Errors . 使用Error而不是Errors


If you really need to do something like this. 如果您确实需要执行以下操作。 I suggest you to use collections.defaultdict . 我建议您使用collections.defaultdict It will allow adding keys with list dynamically. 它将允许动态添加带有list键。

from collections import defaultdict
err = defaultdict(list)

for warning in warnings:
    if warning.status:
        err['error_numbers'].append(warning.error_number)
        err['error_messages'].append(warning.error_message)
        err['datetime'].append(warning.datetime)

But again, it seems like you are trying to achieve something hacky. 但是,再次看来,您正在尝试实现某些目标。 You should probably rethink your needs and approach. 您可能应该重新考虑您的需求和方法。


After all this should print out a key and a list for each keys. 毕竟,这应该打印出一个键和每个键的列表。

<ul>
{% for key, values in err.iteritems %}
 <li>{{key}}:    #edited here, 1 "}" was missing
     {% for value in values %}{{value}}{% endfor %}
 </li>
{% endfor %} 
</ul>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM