【问题标题】:Django : How to use select_related for a OneToOneField?Django:如何将 select_related 用于 OneToOneField?
【发布时间】:2016-12-06 17:09:55
【问题描述】:

我用related_name='children' 在子模型中创建了一个OneToOneField(parent)。在我看来,我使用select_related 来获取查询集。但是在我的页面中,与父级关联的子级列表显示为空。

模型.py:

class Parent(models.Model):
    item = models.CharField(max_length=20)

class Child(models.Model):
    parent = models.OneToOneField(Parent, unique = True, related_name = 'children')
    price = models.IntegerField()

views.py:

def live_prices(request):
    parent_queryset = Parent.objects.all().select_related('children')
    return render(request, 'live_prices.html', 'parent_queryset' : parent_queryset)

模板:

{% for parent in parent_queryset %}
{% child in parent.children.all %}
{{ child.price }}
{% endfor %}
{% endfor %}

【问题讨论】:

  • @Bobort,谢谢,我已经改了

标签: django django-models django-views one-to-one django-select-related


【解决方案1】:

这是一对一的字段,因此您只需访问parent.children(因为您有related_name='children')而不是循环访问parent.children.all()

由于只有一个孩子,我将删除related_name='children',然后您将访问parent.child 而不是parent.children。一对一字段也不需要unique=True

parent = models.OneToOneField(Parent)

然后,在您的模板中:

{% for parent in parent_queryset %}
    {{ parent.child.price }}
{% endfor %}

请注意,使用select_related 不会改变您访问模板中对象的方式,它只会减少 SQL 查询的数量。

【讨论】:

    猜你喜欢
    • 2013-01-01
    • 2011-10-17
    • 2016-01-18
    • 1970-01-01
    • 2011-10-01
    • 2015-02-02
    • 1970-01-01
    • 2014-07-23
    • 2016-10-05
    相关资源
    最近更新 更多