How to display Foreignkey Data in Django html page?

前端 未结 2 1143
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-25 12:19

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

相关标签:
2条回答
  • 2021-01-25 12:44

    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>
    
    
    0 讨论(0)
  • 2021-01-25 12:49

    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.

    0 讨论(0)
提交回复
热议问题