I need a one to many relationship between 3 tables

0

Hello, I have the table People, Vehicles and Monthly who are the users that pay per month the precise stamping that each person can have more than one vehicle, but when registering in the monthly table when selecting a persona appear in the other ampo only the cars that it has, as it is now, all the cars of all the world are appearing.

I'm a beginner and need detailed explanations, thanks for help and patience.

Models.py

TATE_CHOICES = (
('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'),
('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'),
('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'),
('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'),
('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'),
('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'),
('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'),
('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'),
('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'),
('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins')
)


class Pessoa(models.Model):
    nome = models.CharField(max_length=50, blank=False)
    email = models.EmailField(blank=False)
    cpf = models.CharField(max_length=11, unique=True, blank=False)
    endereco = models.CharField(max_length=50)
    numero = models.CharField(max_length=10)
    bairro = models.CharField(max_length=30)
    telefone = models.CharField(max_length=20, blank=False)
    cidade = models.CharField(max_length=20)
    estado = models.CharField(max_length=2, choices=STATE_CHOICES)

    def __str__(self):
         return str(self.nome) + ' - ' + str(self.email) 


class Veiculo(models.Model):
    marca = models.ForeignKey(Marca, on_delete=models.CASCADE, blank=False)
    modelo = models.CharField(max_length=20, blank=False)
    ano = models.CharField(max_length=7)
    placa = models.CharField(max_length=7)
    proprietario = models.ForeignKey(
        Pessoa, on_delete=models.CASCADE, blank=False, )
    cor = models.CharField(max_length=15, blank=False)


def __str__(self):
    return self.modelo + ' - ' + self.placa

views.py

@login_required
def mensalista_novo(request):
    if request.method == 'POST':
        form = MensalistaForm(request.POST or None)
        if form.is_valid():
            form.save()
            return redirect('core_lista_mensalista')
    else:
        form = MensalistaForm
    return render(request, 'core/lista_mensalistas.html', {'form': form})
    
asked by anonymous 11.12.2018 / 09:26

1 answer

0

So I realized that at this point, trying to relate two tables in a relationship of NN, that is, one person can have several cars, and one car can have several people, for a better database structure, part where you have the foreign key for the person and another for the car. And for your doubt, where in the car dropdown appears depending on the person you choose, I advise you to read this tutorial, it may help.

link

    
20.12.2018 / 12:33