当用相同模型的列的单词进行搜索时,它会很好地搜索并正确返回结果,但是如果使用与外键对应的名称进行搜索(在这种情况下,我们要通过“站”进行搜索)具有 Station 模型外键的安装模型),它返回以下错误:
错误:
文件安装>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
文件安装 > 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)
站文件> 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)
作为外键,它按以下方式放置并且可以完美运行:
变化是: