Django从查询到dict的dict

时间:2015-03-07 11:25:52

标签: django dictionary

我有3个型号:

class LawTt(models.Model):
    tt = models.CharField()
    txt = models.TextField()
    parent = models.ForeignKey('self', related_name='children', blank=True, null=True)
    rank = models.ForeignKey(LawRank)

    def get_law(self):
        return Law.objects.filter(law_tt=self)

class Law(models.Model):
    tt = models.CharField()
    txt = models.TextField()
    law_tt = models.ForeignKey(LawTt)

    def get_item(self):
        return LawItm.objects.filter(law=self)

class LawItm(models.Model):
    law = models.ForeignKey(Law)
    txt = models.TextField()

views.py:

class ViewLaw(ListView):
    model=Law
    context_object_name = 'law'
    ...

我的经验允许:

{% if law.all.0.law_tt.parent.parent %}
    {{law.all.0.law_tt.parent.parent.rank}}
{%endif%}
{% if law.all.0.law_tt.parent %}
    {{law.all.0.law_tt.parent.rank}}
{%endif%}
{% if law.all.0.law_tt %}
    {{law.all.0.law_tt.rank}}
{% endif %}
{% for n in law %}
    {{n.txt|safe}}
        {% for i in n.get_item %}
            {{i.txt|safe}}
        {% endfor %}
    </div>
{% endfor %}

但是对于太多SQL查询的这种体验。这很糟糕。 我得到的查询更少。所以,我认为需要字典,我的解决方案。我需要这个:

[{
    'title_one': 'bla_one1', 
        'two': [
        {'title_two': 'bla_two1',},
        {'title_two': 'bla_two2',},
        {'title_two': 'bla_two3',},
    ],
    'title_one': 'bla_one2', 
        'two': [
        {'title_two': 'bla_two4',},
        {'title_two': 'bla_two5',},
        {'title_two': 'bla_two6',},
    ]
}]

帮我理解这个

更新

LawTt model: name law or section or paragraph
LawRank: simple drop-down list (paragraph, section...)
Law: article law
LawItm: item law

我想要的不仅仅是我的问题。可以使用一个查询进行:

Name Law
    Section 1. name section 1
        Paragraph 1. name paragraph 1
            Article 1. name article 1
                Item 1: name item 1
                Item 2: name item 2
                Item 3: name item 3
                ...
            Article 2. name article 2
                Item 1: name item 1
                ...
        Paragraph 2. name paragraph 2
            Article 3. name article 3
                Item 1: name item 1
                ...
                Item 2: name item 2
            Article 4. name article 4
    Section 2. name section 2
        ...may be have not paragraph (or and section)
        Article 5. name article 5
            Item 1: name item 1
        Article 6. name article 6
            ...

0 个答案:

没有答案