gpt4 book ai didi

Django : How to use select_related for a OneToOneField?

转载 作者:行者123 更新时间:2023-12-03 19:54:12 28 4
gpt4 key购买 nike

我用 related_name='children' 在 Child 模型中创建了一个 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()

View .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 %}

最佳答案

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

由于只有一个 child ,我将删除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 查询的数量。

关于 Django : How to use select_related for a OneToOneField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38701919/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com