I want to get data from related foreign-key models, but I am unable to get data from the related model, Please let me know how I can do it. I want to display name
v
First of all you have to fix your syntax error:
def display_data(request, id):
test_display = Model2.objects.filter(pk=id).first()
context = {
'test_display': test_display
}
return render(request, 'page.html', context)
# render instead of ender
second of all try to access the Queryset like so:
<p>{{ test_display.name }}</p>
First, instead of filter(...).first()
, use get()
or get_object_or_404() method:
from django.shortcuts import get_object_or_404
def display_data(request, id):
test_display=get_object_or_404(Model1.objects.prefetch_related('model_one'), pk)
# or Model1.objects.prefetch_related('model_one').get(pk=pk)
return render(request, 'page.html', {'test_display':test_display})
And in the template, use reverse relation to query Model1 instances:
{% for object in test_display.model_one.all %}
{{ object.name }}
{% endfor %}
As the relation between Model1 and Model2 is many to one due to ForeignKey, you will get multiple Model1 objects from reverse querying Model2 instance. If you want only one object to stored for Model2, then consider using OneToOne relation.