I have a project in Django, with data in a Postgres database.
I want to create a form with a ModelChoiceField where I can select the data obtained in a previous queryset.
When I make the queryset to get data from the database:
list_result_queryset = BdimMaestraDatos.objects.filter(fecha_baja__isnull=True).values_list('nombre').distinct()
I get this result:
<QuerySet [('PEDRO',), ('JUAN',), ('ANDRES',), ('PABLO',), ('SOFIA',)]>
And when I show the results in the de template, they are offered but with a "dirty" format like parenthesis, coma, etc.
Please, How can I show it in the form?ModelChoiceField query option only the names PEDRO, JUAN, PABLo, etc and not ('PEDRO',), ('JUAN',), etc.?
This is my form.py
code
from django import forms
from .models import BdimMaestraDatos,
lista_queryset_nombres_activos = BdimMaestraDatos.objects.filter(fecha_baja__isnull=True).values_list('nombre').distinct()
print('Resultado Queryset values list: %s' %lista_queryset_nombres_activos)
class MaestraDatosForm(forms.Form):
Seleccionar_Nombre = forms.ModelChoiceField(label="Nombre", queryset=lista_queryset_nombres_activos)
This is my BdimMaestraDatos model
class BdimMaestraDatos(models.Model):
nombre = models.CharField(db_column='NOMBRE', max_length=32, blank=True, null=True) # Field name made lowercase.
cc = models.CharField(db_column='CC', max_length=2, blank=True, null=True) # Field name made lowercase.
estado = models.DecimalField(db_column='ESTADO', max_digits=1, decimal_places=0, blank=True, null=True) # Field name made lowercase.
red = models.CharField(db_column='RED', max_length=32, blank=True, null=True) # Field name made lowercase.
ger = models.CharField(db_column='GER', max_length=32, blank=True, null=True) # Field name made lowercase.
est = models.TextField(db_column='EST', blank=True, null=True) # Field name made lowercase. This field type is a guess.
fecha_baja = models.DateField(db_column='FECHA_BAJA', blank=True, null=True) # Field name made lowercase.
fecha_alta = models.DateField(db_column='FECHA_ALTA', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'BDIM_MAESTRA_DATOS'
Thanks
At the end I solved my problem, and now data displayed in the forms.ModelChoiceField are clean.
The solution was add the argument flat=True
in the value_list after the field that is filtered.
list_result_queryset = BdimMaestraDatos.objects.filter(fecha_baja__isnull=True).values_list('nombre',**flat=True).distinct()
The result returned is that one:
<QuerySet ['PEDRO', 'JUAN', 'ANDRES', 'PABLO', 'SOFIA']>
Thanks to everyone!