Hi team,
I need help with the following the issue explained below:
- I have two models created in Django models; “Membro” & “Setor” related to tables in postgresql “c_membro” and “c_setor” respectively.
- c_membro handle workers and c_setor handle the area the workers belong to.
- Originally the primary key for table “c_setor” was id column (type: varchar) and I have a foreign key on table “c_membro” using “id” column from c_setor with column “setor_id” on “c_membro” table. (Originally scripts below)
- On “c_setor” table I added a new column “sector_id” (Type: serial4) and set this new column as primary key.
- On table c_membro was added a new column “sector_id” and set as a new foreign key with c_setor.sector_id column. (see new scripts below)
- Note I did those changes directly on data base, then I added the code on python models and makemigrations and migrate --fake to add those fileds to my model (probably did this is not the best way)
- The issue I have is that now when I check the admin session in dejango web the sector_id column returns the entire row referenced not the sector_id value itself.
→ Originaly code on Django project
Models.model
class Setor(models.Model):
id = models.CharField(primary_key=True, max_length=255)
nome = models.CharField(max_length=100)
class Meta:
db_table = 'c_setor'
verbose_name = 'Setor'
verbose_name_plural = 'Setors'
def __str__(self):
return f"{self.nome}"
class Membro(models.Model):
id = models.CharField(primary_key=True, max_length=255)
nome = models.CharField(max_length=255)
setor = models.ForeignKey(Setor, on_delete=models.CASCADE, related_name='c_membro', null=True)
cargo = models.ForeignKey(Cargo, on_delete=models.CASCADE, related_name='c_membro', null=True)
email = models.CharField(max_length=255) # Adicione o campo de email
supervisor = models.CharField(max_length=255)
area = models.CharField(max_length=255)
class Meta:
db_table = 'c_membro'
verbose_name = 'Membro'
verbose_name_plural = 'Membros'
def __str__(self):
return f"{self.id} - {self.nome} - {self.email}"
#----------------------------------------------------------------------------
--View.py
def membros_view(request):
membros = Membro.objects.all()
setores = Setor.objects.all() # Recupere a lista de todos os setores
setor_filtrado = request.GET.get('setor') # Obtenha o valor do setor selecionado no filtro
if setor_filtrado: # Se um setor foi selecionado no filtro
membros = membros.filter(setor_id=setor_filtrado) # Filtrar os membros pelo setor selecionado
membros = membros.order_by('nome') # Ordenar os membros pelo nome em ordem alfabética
#print('hola:', setor_filtrado)
return render(request, 'membros.html', {'membros': membros, 'setores': setores, 'setor_filtrado': setor_filtrado})
#I have no views for c_setor table.
#------------------------------------------------------------------------------------------------------
--class MembroAdmin
class MembroAdmin(admin.ModelAdmin):
list_display = ('id', 'nome', 'setor', 'cargo')
list_filter = ('setor', 'cargo')
search_fields = ('id', 'nome')
def get_list_display(self, request):
# Define as colunas que você deseja exibir em cada linha
# Exemplo: dividir em 3 colunas
columns = 4
# Obtém a lista padrão de campos de exibição
list_display = super().get_list_display(request)
# Divide a lista de campos em várias listas de acordo com o número de colunas
column_lists = [[] for _ in range(columns)]
for i, field_name in enumerate(list_display):
column_lists[i % columns].append(field_name)
# Retorna a lista de campos dividida em colunas
return sum(column_lists, [])
admin.site.register(Membro, MembroAdmin)
-- on Form.py
class MembroForm(forms.ModelForm):
class Meta:
model = Membro
fields = ['id', 'nome', 'setor', ''
''] # Lista dos campos que você deseja editar
widgets = {
'setor': forms.Select(attrs={'class': 'form-control'}),
'cargo': forms.Select(attrs={'class': 'form-control'}),
}
class SetorForm(forms.Form):
setor = forms.ModelChoiceField(queryset=Setor.objects.all(), empty_label=None)
→ changed mentioned on code on Django project (item 4 and 5)
Models.model
class Setor(models.Model):
id = models.CharField(max_length=150)
nome = models.CharField(max_length=100)
sector_id = models.AutoField(primary_key=True)
description = models.CharField(max_length=150)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name = 'se_created_by')
created_on = models.DateTimeField(auto_now_add=True, blank=True, null=True)
last_modified_by = models.ForeignKey(User, on_delete=models.CASCADE, max_length=7, blank=True, null=True,related_name = 'se_last_modified_by')
last_modified_on = models.DateTimeField(auto_now=True, blank=True, null=True)
status_ind = models.SmallIntegerField(blank=True, null=True)
class Meta:
db_table = 'c_setor'
verbose_name = 'Setor'
verbose_name_plural = 'Setors'
def __str__(self):
return f"{self.nome} - {self.sector_id} = {self.created_on} = {self.created_by} - {self.last_modified_on} - {self.last_modified_by}"
class Membro(models.Model):
id = models.CharField(primary_key=True, max_length=255)
nome = models.CharField(max_length=255)
setor = models.CharField(max_length=50, null=True)
#setor = models.ForeignKey(Setor, on_delete=models.CASCADE, related_name='c_membro', null=True)
cargo = models.ForeignKey(Cargo, on_delete=models.CASCADE, related_name='c_membro', null=True)
email = models.CharField(max_length=255) # Adicione o campo de email
supervisor = models.CharField(max_length=255)
area = models.CharField(max_length=255)
sector_id = models.ForeignKey(Setor, on_delete=models.CASCADE, related_name='c_membro', null=True)
created_on = models.DateTimeField(auto_now_add=True, blank=True, null=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True, related_name='me_created_by')
last_modified_on = models.DateTimeField(auto_now=True, blank=True, null=True)
last_modified_by = models.ForeignKey(User, on_delete=models.CASCADE, max_length=7, blank=True, null=True, related_name='me_last_modified_by')
status_ind = models.SmallIntegerField(blank=True, null=True)
class Meta:
db_table = 'c_membro'
verbose_name = 'Membro'
verbose_name_plural = 'Membros'
def __str__(self):
return f"{self.id} - {self.nome} - {self.email}"
#----------------------------------------------------------------------------
--View.py
def membros_view(request):
membros = Membro.objects.all()
setores = Setor.objects.all() # Recupere a lista de todos os setores
setor_filtrado = request.GET.get('setor') # Obtenha o valor do setor selecionado no filtro
if setor_filtrado: # Se um setor foi selecionado no filtro
membros = membros.filter(sector_id=setor_filtrado) # Filtrar os membros pelo setor selecionado
#print('Hola:', membros)
membros = membros.order_by('nome') # Ordenar os membros pelo nome em ordem alfabética
#print("hola:", setor_filtrado)
return render(request, 'membros.html', {'membros': membros, 'setores': setores, 'setor_filtrado': setor_filtrado})
#I have no views for c_setor table.
#------------------------------------------------------------------------------------------------------
--class MembroAdmin
class MembroAdmin(admin.ModelAdmin):
def created_date(self, obj):
return obj.created_on.strftime('%d-%m-%Y')
def updated_date(self, obj):
return obj.last_modified_on.strftime('%d-%m-%Y')
list_display = ('id', 'nome', 'sector_id', 'cargo', 'created_date', 'created_by', 'updated_date', 'last_modified_by', 'status_ind')
#list_display = ('id', 'nome', 'setor', 'cargo', 'email', 'supervisor', 'area', 'sector_id', 'created_date', 'created_by', 'updated_date', 'last_modified_by', 'status_ind')
list_filter = ('sector_id', 'cargo')
search_fields = ('id', 'nome')
def get_list_display(self, request):
# Define as colunas que você deseja exibir em cada linha
# Exemplo: dividir em 3 colunas
columns = 9
# Obtém a lista padrão de campos de exibição
list_display = super().get_list_display(request)
# Divide a lista de campos em várias listas de acordo com o número de colunas
column_lists = [[] for _ in range(columns)]
for i, field_name in enumerate(list_display):
column_lists[i % columns].append(field_name)
# Retorna a lista de campos dividida em colunas
return sum(column_lists, [])
admin.site.register(Membro, MembroAdmin)
-- No changes on Form.py -
class MembroForm(forms.ModelForm):
class Meta:
model = Membro
fields = ['id', 'nome', 'setor', ''
''] # Lista dos campos que você deseja editar
widgets = {
'setor': forms.Select(attrs={'class': 'form-control'}),
'cargo': forms.Select(attrs={'class': 'form-control'}),
}
class SetorForm(forms.Form):
setor = forms.ModelChoiceField(queryset=Setor.objects.all(), empty_label=None)
On image below you could find how it shown the column setor before change and how it shown the new column added sector_id