How to fetch data from different tables in Django?

how to get data from database in django view
how to fetch data from mysql database in django
django create multiple objects at once
how to fetch data from sqlite database in django
django update multiple records with different values
django join multiple tables
django update multiple objects at once
how to create multiple tables in django

I am new to Django and Python,

I have a table for clients, and one for trips. I can display the clients on the clients page, and the same for the trips.

But on the clients page, I want to show all the trips that are linked to each client. And this is where I hit a wall.

This is my models.py

from django.db import models
from django.core.validators import RegexValidator


# Create your models here.

class Clientes(models.Model):
    nome = models.CharField(max_length=30)
    apelido = models.CharField(max_length=30)
    morada = models.CharField(max_length=200)
    tel = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{1,10}$')])
    nif = models.CharField(max_length=9, validators=[RegexValidator(r'^\d{1,10}$')])

    def __str__(self):
        return "%s %s" % (self.nome, self.apelido)

    class Meta:
        verbose_name_plural = "Clientes"

class Viagem(models.Model):
    trip_id = models.CharField(max_length=30)
    cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE)
    comp = models.CharField(max_length=30)
    data = models.DateField()
    destino = models.CharField(max_length=30)

    def __str__(self):
        return self.trip_id

    class Meta:
        verbose_name_plural = "Viagens"

This is my views.py

from django.shortcuts import render
from django.http import HttpResponse
from .models import Clientes, Viagem

# Create your views here.

def index(request):
    ls= Clientes.objects.all()    
    context = {'ls': ls}
    return render(request, "booking/home.html", context)

def cliente(request, id):
    ls= Clientes.objects.filter(id=id)
    context = {'ls': ls}
    return render(request, "booking/cliente.html", context)

def trip(request):
    ls= Viagem.objects.all()    
    context = {'ls': ls}
    return render(request, "booking/trip.html", context)

and this is the table on the home.html

    <table id="selector" class="table is-fullwidth is-hoverable">
    <thead>
      <tr>
        <th>Nome</th>
        <th>Apelido</th>
        <th>Morada</th>
        <th>Telemóvel</th>
        <th>NIF</th>
        <th>Viagens</th>
      </tr>
    </thead>
    <tbody>
        {% for ls in ls %}
      <tr>
        <td>{{ls.nome}}</td>
        <td>{{ls.apelido}}</td>
        <td>{{ls.morada}}</td>
        <td>{{ls.tel}}</td>
        <td>{{ls.nif}}</td>
        <td>{{ls.trip_id}}</td>
      </tr>
      {% endfor %} 
    </tbody>
</table>

I assume it has something to do with ForeignKey, but a ForeignKey on the first class won't work.

I thought about creating a new def on the views.py using the Viagem table and a diferent context, but that also doesn't seem to be the solution.

So, anyone can point me in the right direction?

In your views.py, specifically the cliente function, you want to add the following line:

viagems=Viabem.objects.filter(cliente=ls)

modify the following line:

ls= Clientes.objects.filter(id=id)

so that it now shows:

ls=Clientes.objects.get(id=id)

and then change your context to equal:

context = {'ls': ls, 'viagems': viagems}

then you will be able to iterate over the different viagems in your html template file with the following kind of structure:

{% for viagem in viagems %}
  {{ viagem.whatever_field }}
{% endfor %}

and that should be it, I believe...

Django get data from multiple tables, I want to fetch and display details(name_project, user_name) from both but it displays only data from Project table in the json file, I want to� Here, it’s printing out the SQL for the initial migration, where Django creates the new table and adds the fields to the table. We can check out what Django created in the database browser (Figure 4.4). Figure 4.4: The event table in the database. You can see Django’s app_model naming convention for table names at work in the table name

Since you are filtering by ID (fetching single object), this is one of the options to go:

views.py

from django.shortcuts import get_object_or_404

def cliente(request, id):
    ls = get_object_or_404(Clientes, id=id)
    trips = obj.viagem_set.all()
    context = {'ls': ls, 'trips': trips}
    return render(request, "booking/cliente.html", context)

template.html

<table id="selector" class="table is-fullwidth is-hoverable">
<thead>
  <tr>
    <th>Nome</th>
    <th>Apelido</th>
    <th>Morada</th>
    <th>Telemóvel</th>
    <th>NIF</th>
    <th>Viagens</th>
  </tr>
</thead>
<tbody>
  <tr>
    <td>{{ls.nome}}</td>
    <td>{{ls.apelido}}</td>
    <td>{{ls.morada}}</td>
    <td>{{ls.tel}}</td>
    <td>{{ls.nif}}</td>
    <td>{% for trip in trips %}{{ trip.id }}{% endfor %}</td>
  </tr>
  {% endfor %} 
</tbody>

While I'm not sure why you need to show record ID's in the table.

Django Data Queries Against Multiple DB Tables, django #multiple #tables #view In this training, we will use one function views that works Duration: 14:04 Posted: Oct 7, 2018 Django uses lowercase table names when it auto-generates table names from models, so this is mainly a consideration if you are overriding the table name via the db_table parameter. Savepoints ¶ Both the Django ORM and MySQL (when using the InnoDB storage engine ) support database savepoints .

@João de Sousa, I found you want to show all trips that are associated with each client.

First of all you have to get a single client by his id obj = clients.objects.get(id = id) then this id pass to referred model like this obj1 = Viagem.objects.filter( id = obj.id)

According to my understanding from your above posted question is that you want to get help about how you get data from reference model/table. Django provides very easy and flexible way to get data from tables.

Feel free to ask any question if you need more clarification.

CRUD multiple records in Django models, Read multiple records with all(), filter(), exclude() or in_bulk() To read multiple records associated with a Django model you can use several methods, which include: all() , filter() , exclude() and in_bulk() . The purpose of the all() method should be self explanatory, it retrieves all the records of a given model. According to my understanding from your above posted question is that you want to get help about how you get data from reference model/table. Django provides very easy and flexible way to get data from tables. Feel free to ask any question if you need more clarification.

Django Models - Python Django Tutorials, You want to describe your data once, not create separate sets of SQL statements for To retrieve all the records in a database table, you use the all() method: >� الدرس رقم 60 من كورس الويب بالبايثون وفي هذا الدرس نقوم بشرح كامل لتالي : درس هام جدا جدا جدا جدا شرح ازاي اجيب

10. How to perform join operations in django ORM?, A SQL Join statement is used to combine data or rows from two or more tables based on a common field between them. Join can be carried out in many ways. A model is the single, definitive source of information about your data. It contains the essential fields and behaviors of the data you’re storing. Generally, each model maps to a single database table. The basics: Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field.

Accessing Related Data Using Django ORM, Notice that in the last two commands we are accessing data stored in a different table i.e blog_author without writing SQL join query. That's the� Welcome to another tutorial of Django web development tutorial series. Today we are going to discuss how to fetch data from the database. Download source code of the project that we created in

Comments
  • I tried your suggestions, but it still returns empty. On the clientes.html page, I have a table with all clients, and at the end a field where I want to output their viagem.trip_id.
  • Well I did have a clarification, first of all. In the first line where I typed Viabem it should (obviously) be Viagem. If you're still having the problem after that I would look into whether or not you have any trips that correspond to the cliente ID.
  • Yes, I corrected it before trying. No luck. And yes, there are trips corresponding to the client, I can query it on the shell.
  • I'm really not sure what to tell you at this point. The code there, as well as the code in the other example here by @Charnel should, presumably, work without issues so long as the database contains the appropriate records... Maybe if I get a chance today I can rewrite everything with catches in case the database is structured wrong and see what that gives you as output, but I'm not sure if that's going to happen or not. I'll try to make time for it here. If you could post your database queries here so I could see all fields of the applicable records it would help, though.
  • I tried your suggestions, but it still retuns empty. On the clientes.html page, I have a table with all clients, and at the end a field where I want to output their trip_id. I also have a page displaying all trips, and I can output the client name, via the ForeignKey.
  • @JoãodeSousa are you sure there are related trips? Can you run it in debug to see trips actually populated?
  • yes there are. I have a page, trips.html, where I display all trips on database.
  • I just noticed your comment about why showing the record id. It's not the record id, it's an ID created by the user, like a "trip name". The goal is that when looking at the clients table, there is the information about the trip_id, that is also a link to the trip info page.
  • ok, can you post an example of populated trips variable? Use breakpoint in debug with evaluating value or use a django shell with running queries with some of the client ID's you are using...or simply put print(trips) and post whatever it prints here.