How to relate two classes in the same Model Django

Asked

Viewed 102 times

1

hello,

I am new to Django and I am trying to get information related to two different classes, with 1 variable as "base" for it. In case I have the Customer and Order class, and I would like to include a field where when selecting the Customer, appears in my Model the address of the same:


class Client(models. Model):

nome = models.CharField('Nome', max_length=50)
nome_fantasia = models.CharField('Nome Fantasia', max_length=50)
endereco = models.CharField('Endereço', max_length=50)
cidade = models.CharField('Cidade', max_length=50)
estado = models.TextField('Estado', max_length=12, choices=UF_CHOICES)

Order class(models. Model):

SIT_CHOICES = ((tirei pra nao ficar grande))

TIPO_CHOICES = (tirei pra nao ficar grande)

numero = models.CharField('Numero', max_length=9, unique=True)
situacao = models.CharField('Situação', max_length=12, choices=SIT_CHOICES)
data = models.DateField()
fornecedor = models.ForeignKey(Fornecedor, on_delete=models.SET(set_default_fornecedor))
cidade = models.CharField('Cidade', max_length=50)
**cidade_cliente = ??????????????**
cliente = models.ForeignKey(Cliente, on_delete=models.SET(set_default_cliente))
preco_produto = models.DecimalField('Preço', max_digits=8, decimal_places=2)
variedade = models.CharField('Variedade', max_length=12)
tipo = models.CharField('Tipo', max_length=12, choices=TIPO_CHOICES)
quantidade_pedido = models.IntegerField('Quantidade Pedido', help_text="Peso em Tonelada")

another question that I have already faced, that I will have several lines for each order, and I need to include also in the Request class "total order" basically would be a sum of all the launches of each order, in a new class that I will create as statement that is, again I come across the need to seek information of another class and demonstrate in this.


Anyway, to scanning the google answers and still not found result.

2 answers

0

Fala Gabriel,

I was able to bring the information to the list_display using the code below, using within the admin.py request class:

def get_cidade(self,obj):
    return obj.fornecedor.cidade
get_cidade.short_description = "Cidade"

0

how there is a connection from one class to another which is Foreignkey

                 cls     cls     atributo

you can access the request.cliente.city

and to access a customer’s requests

for p in cliente.pedido_set.all():
   print(p)

Browser other questions tagged

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