When a search is made by word of a column of the same model, it searches well and returns the results correctly, but if it is searched with a name that corresponds to a foreignkey (in this case we want to search by "station" of the Installation model that has foreignkey to the Station model), it returns the following error:
Mistake:
File Installation > views.py
class StationList(ListView):
model = Instalacion
template_name = 'instalacion/instalacion_list.html'
def get_queryset(self):
name = self.request.GET.get('kword', '')
if name:
object_list = self.model.objects.filter(estacion__icontains = name)
else:
object_list = self.model.objects.all()
return object_list
File Installation > models.py
class Instalacion(models.Model):
tipo_instalacion = models.ForeignKey(TipoInstalacion, on_delete=models.CASCADE,null=True)
estacion = models.ForeignKey(Station, on_delete=models.CASCADE,null=True, blank=True)
observaciones = models.TextField('Observaciones',null=True, blank=True)
class Meta:
verbose_name = 'Instalación'
verbose_name_plural = 'Instalaciones'
ordering = ['estacion']
def __str__(self):
return str(self.estacion) + ' - ' + str(self.tipo_instalacion)
Station file > models.py
class Station(models.Model):
fecha_actuacion = models.DateTimeField ('Fecha edición',null=True, blank=True)
author = models.ForeignKey('auth.User', on_delete=models.CASCADE,null=True, blank=True)
codigo = models.CharField('Código',max_length=50,null=True, blank=True)
name = models.CharField('Nombre',max_length=50,null=True, blank=True)
objects = StationManager()
class Meta:
verbose_name = 'Estación'
verbose_name_plural = 'Estaciones'
def __str__(self):
#return [self.name,self.area,self.codigo]
return str(self.id) + '-' + str(self.name)
Being a foreignkey, it is put in the following way and it works perfectly:
What changes is: