collect table field value

I have two queries that I think may be related.
I have a form where there are some fields that are entered by the user and others that are assigned directly by the app by default. These default fields also appear on the form through with code:

def get_initial(self):
        return {
            "atiende": self.request.user,
            "delegacion_departamento": self.request.user.cod_departamento_id

The cod_departamento_id field is from the users table but I would like to take a field from another table, specifically a table called department that is also in the same database
The thing is like indicating instead of


let it be something like that
That doesn’t work for me.

thank you

Specifically, which “department_name_field” do you want? I’m assuming you have multiple rows in department_table_name

Generally, you need to write a query to retrieve the data you want.

Is there some relationship between the current user (self.request.user) and the data you’re looking for?

(It may help if you posted the relevent models here.)

I want to do a get of the department that has the authenticated user

If the two tables are related, in the users table there is the field cod_departament that relates to the department table, where there is the full name.


class departamento(models.Model):
    codigo = models.IntegerField('Codigo Departamento')
    nombre_departamento = models.CharField('Nombre Grupo', max_length=254,unique = True)

class Usuario(AbstractBaseUser, PermissionsMixin):
    username = models.CharField('Nombre de usuario',unique = True, max_length=100)
    email = models.EmailField('Correo Electrónico', max_length=254,unique = True)
    nombres = models.CharField('Nombres', max_length=200, blank = True, null = True)
    apellidos = models.CharField('Apellidos', max_length=200,blank = True, null = True)
    imagen = models.ImageField('Imagen de Perfil', upload_to='perfil/', max_length=200,blank = True,null = True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    objects = UsuarioManager()
    cod_departamento = models.ForeignKey(departamento, null=True,blank=True,on_delete=models.CASCADE)
    cod_grupo = models.ForeignKey(grupos, null=True,blank=True,on_delete=models.CASCADE)

If you have an instance of Usuario named user, then the related object of type departamento would be referenced as user.cod_departamento. (cod_departamento is the name of the ForeignKey referencing the departamento model.)

If you have an instance of departamento named un_departamento, then you would reference the nombre_departamento field as un_departamento.nombre_departamento.

Putting those two together means that given a Usuario named user, you would access that character field as user.cod_departamento.nombre_departamento.

Perfect, now I understand.

Thank you so much.