在django中搜索两个或多个模型之间的查询集以搜索表单

时间:2015-06-12 00:11:33

标签: django django-forms django-class-based-views

我在django中构建一个搜索表单,我正在使用过滤器查询集,这个表单就像一个"高级搜索表单",我的意思是,表单可能有两个以上的输入,但问题是每个输入相应的不同模型的字段,我有这个,如果表单只有一个输入一个模型,工作正常:

class InfoPredioGeneral(models.Model):
        nombre_predio = models.CharField(max_length=30)

class Propietario(models.Model):
        predio = models.ForeignKey(InfoPredioGeneral,blank=True,null=True,related_name='predio_propietario+')
        tipo_identificacion = models.ForeignKey(TipoIdentificacion,related_name='tipo identificacion+',blank=True,null=True)

如果我有这个型号:

InfoPredioGeneral

在post方法中,如何以Propietarioidentificacion的相同形式搜索?例如过滤器,其中nombre_predio精确到" predio proof"和tipo _ Propietario完全匹配" 123"?如您所见ForeignKey有一个InfoPredioGeneral @Override public Thread newThread(Runnable r) { explorer = new QRExplorer(); // extends Observable observador = new Observador(explorer); //implements Observer explorer.addObserver(observador); Thread t = new Thread(r); return t; }

1 个答案:

答案 0 :(得分:1)

您正在寻找多对一的关系

https://docs.djangoproject.com/en/1.8/topics/db/examples/many_to_one/

您已将related_name设置为“predio_propietario +”,并且最后使用“+”表示此模型没有向后关系

有你的例子:

queryset = Propietario.objects.filter(predio__nombre_predio__iexact=request.POST['nombre_predio'])

额外:

class C(models.Model):
    c_text = models.CharField(max_length=100)

class B(models.Model):
    b_text = models.CharField(max_length=100)

class A(models.Model):
    b = models.ForeignKey(B)
    c = models.ForeignKey(C)

queryset将如下所示:

queryset = A.objects.filter(b_btext__isexact="your b text", c_ctext__isexact="your c text")
相关问题