简体   繁体   中英

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:

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?

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.

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).

Example (as I use at the moemnt) bellow does not print anything at all.

<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 . 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 .


If you really need to do something like this. I suggest you to use collections.defaultdict . It will allow adding keys with list dynamically.

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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