A left outer reverse select_related in Django?

后端 未结 5 2011
旧巷少年郎
旧巷少年郎 2020-12-06 04:24

Imagine the following model:

class Parent(Model):
    ...

class Child(Model)
    father = ForeignKey(Parent)
    ...

Some parents have chi

相关标签:
5条回答
  • 2020-12-06 04:55

    in django 1.3

    Child.objects.select_related('father')
    #sql: select * from app_child left join app_parent  on child_father_id=parent_id
    
    0 讨论(0)
  • 2020-12-06 05:02

    In this case, I think the best thing to do is list the children, then get the parent from them, like this:

    children = Child.objects.filter(...).select_related('parent').order_by('parent')
    

    Then in the template, possibly use a regroup (note the order_by above):

    {% regroup children by parent as parents %}
    <ul>
    {% for parent in parents %}
        <li>{{ parent.grouper }}
        <ul>
        {% for child in parents.list %}
        ...
        {% endfor %}
        </ul>
        </li>
    {% endfor %}
    </ul>
    
    0 讨论(0)
  • 2020-12-06 05:02

    I think you are looking for select_related()

    0 讨论(0)
  • 2020-12-06 05:04

    Starting from Django 1.4 prefetch_related does what you want.

    Parent.objects.prefetch_related('child_set')
    

    Related(!) django docs : https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related.

    0 讨论(0)
  • 2020-12-06 05:07

    Sorry to once again post a link to my blog, but I have written about a technique to simulate select_related on backwards relationships.

    0 讨论(0)
提交回复
热议问题