How to relate two form Fields in Django?

Asked

Viewed 41 times

-1

Good afternoon! I am new to Jango and I am creating a system that will serve as a spreadsheet to help in the analysis of some demands.

The demands will be a certificate called CAT requested by architects. That is, a CAT will be linked to only one architect, but an architect may have several Rcts and I would like to know how to save this relationship in the database and how to read it later.

O model do Arquiteto

O model da CAT

A view, que está basicamente recebendo os dados

inserir a descrição da imagem aqui

What I want to do is that when registering the CAT and the professional, one is linked to the other and I can then search all the CAT-As linked to a professional and can check which professional linked to a CAT. But using only the foreignkey the two are not linked, and in admin appears a list of all registered professionals for me link to CAT.

inserir a descrição da imagem aqui

1 answer

0


In fact, the correct way to implement it is by using a Foreign Key (foreign key) to the Architect from CAT. According to what you described, your templates are correct.

What appears to you in Admin, with the list of architects for you to link to CAT, is also correct. You must choose one of the architects from the list and save the CAT, so this architect is linked to the CAT. Logo, you already have automatically which architect is linked to the CAT in question.

Now, to check all the Cats that are linked to a professional, it’s a little bit more complicated. You need to add the method below to the class Arquiteto:

def get_cats(self):
        return list(Cat.objects.filter(profissional_id=self.id))

This function returns a list of all Cats linked to a particular architect. To do this, just know the ID of the professional in question. How this is a method of the class itself Arquiteto, the ID we already know: self.id.

The professional_id field is a field automatically created by Django in the class Cat due to the use of Foreign Key.

If you read a little English, I highly recommend Django’s official documentation on foreign keys: https://docs.djangoproject.com/pt-br/3.1/ref/models/fields/#Django.db.models.Foreignkey

  • Your answer has made me very clear, Wensiso. Thank you! This system would be used by analysts and the idea would be that they would not need to use the admin, but that the linking would be done automatically. Would that be possible? If it is not possible to do it by Jango, it would be possible to do it using another technology?

Browser other questions tagged

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