Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django : How to use select_related for a OneToOneField?

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 %}
like image 872
sumanth Avatar asked Dec 24 '22 03:12

sumanth


1 Answers

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.

like image 118
Alasdair Avatar answered Feb 11 '23 15:02

Alasdair