4

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 %}
Alasdair
  • 298,606
  • 55
  • 578
  • 516
sumanth
  • 751
  • 2
  • 15
  • 34

1 Answers1

10

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.

sumanth
  • 751
  • 2
  • 15
  • 34
Alasdair
  • 298,606
  • 55
  • 578
  • 516