We have 2 models in our Django projects Model1 and Model2, and we have ForeignKey relation of Model1 in Model2, and we want to get data on Model2 using Model1 in our views function, lets check the code…

Here is our models.py file…

class Customer(models.Model):

class Model1(models.Model):

class Model2(models.Model):
    model1=models.Foreignkey(Model1, related_name='model_one', on_delete=models.CASCADE)
   customer=models.Foreignkey(Customer, related_name='customer_data', on_delete=models.CASCADE)

In the above code Model2 have the ForeignKey of Model1, now check our views.py file…

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 }}
    {{ object.customer.name }} # this will display Customer name from Customer Model
{% 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.


Please enter your comment!
Please enter your name here