简体   繁体   中英

How to fetch data from different 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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM