Django从多个模型中过滤数据

时间:2013-06-01 09:58:41

标签: django python-2.7 django-models django-templates django-views

这里我使用了4个模型,一个是基础模型,另外三个是从基础模型派生的派生模型。我想在这三个模型之间过滤数据,其中引用id是常见的。我在下面添加了代码供您参考。

models.py

class User(models.Model):
    name = models models.CharField(max_length=20)

class JSDetails(models.Model):
    user = models.ForeignKey(User, unique=True)
    visiblity = models.BooleanField(default=True)

class JSPersonal(models.Model):
    user = models.ForeignKey(User, unique=True)
    JS = models.ForeignKey(JSDetails, unique=True)
    country = models.CharField(max_length=100)

class JSSkills(models.Model):
    user = models.ForeignKey(User, unique=True)
    JS = models.ForeignKey(JSDetails, unique=True)
    skill = models.CharField(max_length=100)

views.py

def Result(request):
    skills = request.GET['skill']
    country = request.GET['country']
    query = Q(skill__icontains=skills )
    query1 = Q(country__icontains=country )
    query2 = Q(visiblity=True)

这两个关键字(技能=“python”,country =“USA”)都可以获得匹配,或者与上述四个模型匹配。它显示结果,如姓名,技能和国家。请帮助我。

1 个答案:

答案 0 :(得分:1)

def Result(request):
    skills = request.GET['skill']
    country = request.GET['country']
    query_skills = Q(jsskills__skill__icontains=skills)
    query_country = Q(jspersonal__country__icontains=country)
    query_visibility = Q(jsdetails__visiblity=True)
    users = User.objects.filter(query_skills | query_country, query_visibility)
    return render_tor_response('sometemplate.html', {'users': users})

然后在模板中,您将循环显示上下文中的users