Django : How to use select_related for a OneToOneField?
Asked Answered
B

1

5

I have created a OneToOneField(parent) in Child model with related_name='children'. In my views, I used select_related to get the queryset. But in my page the list of children associated to a parent shows empty.

Models.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)

Template:

{% for parent in parent_queryset %}
{% child in parent.children.all %}
{{ child.price }}
{% endfor %}
{% endfor %}
Butterball answered 1/8, 2016 at 14:50 Comment(1)
@Bobort, Thanks, I have changed itButterball
A
12

It's a one to one field, so you simply access parent.children (because you have related_name='children') instead of looping through parent.children.all().

Since there is only one child, I would remove the related_name='children', then you will access parent.child instead of parent.children. You don't need unique=True for a one-to-one field either.

parent = models.OneToOneField(Parent)

Then, in your template:

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

Note that using select_related does not change the way you access the objects in the template, it just reduces the number of SQL queries.

Airline answered 1/8, 2016 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.