Home > Software engineering >  How to query data from two tables using django?
How to query data from two tables using django?

Time:03-07

I have mySQL tables connected with "one to many" relationship

params of the main table are:

  • name
  • age
  • height

params of the second table are:

  • f_name (as foreign key of )
  • salary_date
  • salary

I already get data from first table using this code:

models.py

from tabnanny import verbose
from django.db import models, connections
from django.urls import reverse


class collection_data(models.Model):
    name = models.CharField(max_length=50)
    age =models.IntegerField()
    height = models.IntegerField()

    class Meta:
        verbose_name = 'Collection Data'



class second_data(models.Model):
    # connect this table with previos
    data = models.ForeignKey(collection_data, on_delete=models.CASCADE)

    salary= models.FloatField(max_length=100)
    salary_date= models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'Frequent Collection Data'
        ordering = ['salary_date']

views.py

from django.views.generic import DetailView

class InfoDetailView(DetailView):
    model = collection_data
    template_name = 'info/Info.html'
    context_object_name = 'info'

urls.py

path('<int:pk>', views.InfoDetailView.as_view(), name="info-data"),

Info.html

<ul >
  <li>{{ info.name }}</li>
  <li>{{ info.age }}</li>
  <li>{{ info.height}}</li>
</ul>

<table>
  <tr>
    <th>Date</th>
    <th>Salary</th>
  </tr>
{% for el in second_data %}
  <tr>
    <td>05/06/2021</td>
    <td>1350$</td>
  </tr>
{% endfor %}
</table>

Result on the page must be: enter image description here

CodePudding user response:

If you want to retrieve all second_data objects related to collection_data in template, you need to use {% for el in info.second_data_set.all %} instead of {% for el in second_data %}. Consider setting related_name attribute of models.ForeignKey() so you can do something like {% for el in info.'related_name'.all %}.

Also try using CamelCase for class names (CollectionData instead of collected_data).

CodePudding user response:

query = second_data.objects.all() 

then in your html file like just write like this way

{% for item in query %}
         {{ item.salary }}
         {{ item.salary_date }}
{{ endfor }}
  • Related