I have a disease table that has only 3 columns:
- The automatic id.
- A code
varchar(10)
. - the name
string
.
But, it has 14197 records.
The problem is that your Primary Key is a foreign key for other models, but it is taking a long time to load it.
Use django
and PostgreSql
, what is the most recommended so that it does not take so long to load it Foreign Key
in the template
?
Models
class Cie10(models.Model):
codigo = models.CharField(max_length=10)
nombre = models.TextField()
def __unicode__(self):
return (u"%s (%s)"%(self.nombre, self.codigo)).strip() or "-"
class EnfermedadGeneral(Enfermedad):
dias = models.IntegerField(validators=[no_negativo])
cie10 = models.ForeignKey(Cie10, verbose_name="diagnóstico Cie10")
soportes = models.FileField(upload_to=crear_ruta_archivo_enfermedad_general, blank=True, null=True)
class Enfermedad(models.Model):
persona = models.ForeignKey(Persona, related_name="enfermo")
responsable = models.ForeignKey(Persona, related_name="responsable")
municipio = models.ForeignKey(Municipio)
zona = models.IntegerField(choices=ZONAS)
sucursal = models.ForeignKey(Sucursal)
area = models.ForeignKey(Area)
cargo = models.ForeignKey(Cargo)
tipo_empleado = models.CharField(max_length=1, choices=TIPO_EMPLEADO)
fecha_ingreso = models.DateField()
fecha_diligenciamiento = models.DateTimeField(auto_now_add=True, blank=True)
fecha = models.DateField(verbose_name="fecha del diagnóstico")
def __unicode__(self):
return (u"%s (%s)"%(self.persona, self.fecha)).strip() or "-"
class Meta:
unique_together = (("persona", "fecha"),)
Form Example
class EnfermedadGeneralForm(forms.ModelForm):
class Meta: model = EnfermedadGeneral
exclude = ('responsable', 'persona', 'sucursal', 'area', 'cargo', 'tipo_empleado', 'fecha_ingreso', 'fecha_diligenciamiento',)
widgets = {
'fecha' : MyDateWidget(),
'municipio': Select2Widget(),
'cie10': Select2Widget(),
'soportes' : MyFileInput(), }
Form in the template
<form class="form-vertical" enctype="multipart/form-data" method="post">{% csrf_token %}
{% bootstrap_form form layout="horizontal" %}
<button class="btn btn-lg btn-primary pull-right" type="submit" onclick="$('#id_dia_semana').attr('disabled', false);">
Registrar <i class="fa fa-check"></i>
</button>
</form>
view example
@login_required
@all_permission_required('novedades.add_enfermedadgeneral')
def crear_enfermedad_general(request, idPersona=None):
persona = None
hoy = datetime.now()
usuario = Persona.objects.get(usuario=request.user)
enfermedadGeneralCreada = request.session.get('nueva_enfermedad_general')
if enfermedadGeneralCreada == True:
del request.session['nueva_enfermedad_general']
if idPersona:
try:
persona = Persona.objects.get(id=idPersona)
except Exception:
return redirect('crear_enfermedad_general')
if request.method == 'POST':
form = EnfermedadGeneralForm(request.POST, request.FILES)
if form.is_valid():
objeto = form.save(commit=False)
objeto.responsable = Persona.objects.get(usuario=request.user)
objeto.persona = persona
objeto.sucursal = persona.sucursal
objeto.area = persona.cargo.area
objeto.cargo = persona.cargo
objeto.tipo_empleado = persona.tipo_empleado
objeto.fecha_ingreso = persona.fecha_ingreso
objeto.soportes = None
objeto.save()
try:
objeto.soportes = request.FILES['soportes']
except Exception:
1
objeto.save()
request.session['nueva_enfermedad_general'] = True
return redirect('crear_enfermedad_general')
form2 = CedulaForm(request.POST)
if form2.is_valid():
persona = form2.cleaned_data['persona']
return redirect('crear_enfermedad_general', persona.id)
else:
form = EnfermedadGeneralForm()
try:
form2 = CedulaForm({'persona': persona.id})
except Exception:
form2 = CedulaForm()
return render(request, 'enfermedad_general.html', {
'enfermedadGeneralCreada': enfermedadGeneralCreada,
'persona': persona,
'form': form,
'form2': form2,
'hoy': hoy,
'usuario': usuario,
})
I'm not 100% sure because
Select2Widget
I don't know the widget, but if it is this one, you are loading the 14 thousand records in the rendering.Perhaps you should change the widget to take you one that does the AJAX search after N characters to:
you can use this
It seems to me that the efficiency of the search is not the responsibility of the application, but of the database.
The most important thing to do efficient/inexpensive queries in a database is to take into account certain things:
And there are other methods, just as important, when things don't just work out.
If your problems exceed this kind of thing, start looking at things like caching in memory.
In order to determine if the problem is in the query or elsewhere, as seems to be the case (namely, the rendering of the select with 14k entries), the Django debug toolbar extension is highly recommended . Among other useful information, it shows you the number of queries made to the database and the number of milliseconds it has taken to execute each one of them.