Home > Blockchain >  Django foreign key display values in detail view
Django foreign key display values in detail view

Time:04-01

I have a main DB table Radni_nalozi (Work Orders) to which I am attaching Stavke (items) by a foreign key. When I go to see details about a specific Work Order I also want to display all the items that are connected to that Work Order by a foreign key.

I tried many different approaches and it seems that I just can't figure it out on my own. I am attaching the code below. In an HTML template, I can only fetch details about specific work orders but not the items.

models.py

views.py

template html

CodePudding user response:

  1. If you are using ForeignKey in django, you can access all rows that are in relationship with one row using "related_name" parameter.To get all the items that are connected to that Work Order(id=1) by a foreign key.

    radni_nalozi_obj = Radni_nalozi.objects.get(id=1)
    radni_nalozi_obj.stavka       //we are using related_name that is mentioned in "Stavke" model for "Artikl" foreignkkey.
    
  2. In your detail view, you may have to modify the context object before returning. enter image description here

CodePudding user response:

Add get_context_data to your detail view in order to get the object and fetch all items related to that obj. Basically, this method replaces the default context provided by the DetailView, so you have to also include the object itself.

class RadniDetailView(DetailView):

    # ..... remain code ......

    def get_context_data(self):
        context = super(RadniDetailView, self).get_context_data()
        radni_obj = self.object # this contain the object that the view is operating upon
        context['object'] = radni_obj # don't forget this also

        # Get all items/Stavke related to the work order/Radni_nalozi
        context['items'] = Stavke.objects.filter(Rn=radni_obj)
        return context

inside HTML you can display all items like so

{% for item in items %}
   {{ item }}
{% endfor %}
  • Related