i have created onetoonefield(parent) in child model related_name='children'
. in views, used select_related
queryset. in page list of children associated 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:
{% parent in parent_queryset %} {% child in parent.children.all %} {{ child.price }} {% endfor %} {% endfor %}
it's 1 one field, access parent.children
(because have related_name='children'
) instead of looping through parent.children.all()
.
since there 1 child, remove related_name='children'
, access parent.child
instead of parent.children
. don't need unique=true
one-to-one field either.
parent = models.onetoonefield(parent)
then, in template:
{% parent in parent_queryset %} {{ parent.child.price }} {% endfor %}
note using select_related
not change way access objects in template, reduces number of sql queries.
Comments
Post a Comment