How to create this type of relationship using Django Models

Asked

Viewed 35 times

0

After seeing a modeling that I should implement in Django, I was a little confused and I will explain what I tried to do and what was sent to me. The following image is the relationship I should implement in Django inserir a descrição da imagem aqui

What I tried to do was:

class Contato(models.Model):
    pessoa = models.OneToOneField(Pessoa)

class Pessoa(models.Model):
    contato = models.ForeignKey(Contato)

But this does not work, both classes are in the same file. I read the documentation of Manytomanyfield, Onetoonefield and Foreignkey, but what makes me confused is the model wanting the varialvel in the two classes, in previous models that I saw existed this same relation, but the varialvel only existed in one of the classes. What is the right way to implement this?

1 answer

2


I understand that a person can have one or more contacts, right?

Take a look below:

from django.db import models

class Pessoa(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=40)

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

class Contato(models.Model):
    contato = models.CharField(max_length=50)
    pessoa = models.ForeignKey(Pessoa, on_delete=models.CASCADE)

    def __str__(self):
        return self.contato

    class Meta:
        ordering = ['pessoa']

I hope it helps.

  • Hello, Paulo, after performing some tests I had already come to the same conclusion as you, so I will consider your answer as the correct one since the implementation was similar. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.