Kravcenko Nikita
Kravcenko Nikita

Reputation: 139

How to query data from two tables using django?

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

params of the main table are:

params of the second table are:

So I need to do something like:

select * from table2
where t_id in( select t_id from table1
   where t_var = 'Alfred'
);

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 class="data">
  <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

Upvotes: 0

Views: 758

Answers (2)

Tanveer
Tanveer

Reputation: 1233

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 }}

Upvotes: 1

Smile23
Smile23

Reputation: 106

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).

Upvotes: 2

Related Questions