简体   繁体   English

Django的。 通过字典中的模型进行迭代

[英]Django. Iterate by models in dictionary

I have two models: 我有两个模型:

class Status(models.Model):

    CHOISES = (
        ('new', 'New'),
        ('in_progress', 'InProgress'),
        .....
    )

    status_type = models.CharField(
        max_length=11,
        choices=CHOISES,
        primary_key=True)

    def __unicode__(self):
        return str(self.status_type)


class Task(models.Model):

    name = models.CharField(max_length=200, blank=False)
    status = models.ForeignKey(Status)

this is part of my view, which return dictionary with keys, based by status model: 这是我视图的一部分,该视图根据status模型返回带有键的字典:

    all_tasks = Task.objects.select_related('status').order_by('status')
    tasks = {status: list(tasks)
         for status, tasks
         in itertools.groupby(all_tasks, lambda x: x.status)
    }

Here is part of dictionary which views function return: 这是字典中查看功能返回的一部分:

{<Status: new>: [<Task: Task object>, <Task: Task object>],
 <Status: in_progress>: [<Task: Task object>,<Task: Task object>],...}

I need to group all tasks models in template by 5 status columns. 我需要按5个status列将模板中的所有tasks模型分组。
So I use this call: 所以我用这个电话:

    {% for item in tasks.new %}
        {{ item.name }}
    {% endfor %}

it doesnt work, because I cant get value from my dictionary, by status object name. 它不起作用,因为我无法通过status对象名称从字典中获取值。
The question is how I can iterate by status object from dict keys, in template? 问题是如何通过模板中的dict键按status对象进行迭代?

I'm not sure what point there is in having a Status model just to store one field. 我不确定仅使用状态模型来存储一个字段有什么意义。 Why not keep that in Task, with the choices defined there? 为什么不将其保留在Task中,并在那里定义选择呢?

Nevertheless, you could fix your immediate problem by grouping by x.status.status , to use the actual charfield value rather than its containing model. 不过,您可以通过按x.status.status分组来解决当前的问题,以使用实际的charfield值而不是其包含的模型。

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

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