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 %}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With