Django查询多个表

时间:2012-01-31 11:23:33

标签: python django

我在编写正确的查询以获取结果时遇到了很多麻烦......

from django.db import models
from django.contrib.auth.models import User

class GeoCatch(models.Model):
    user_me = models.ForeignKey(User, null=True, related_name='me')
    user_he = models.ForeignKey(User, null=True, related_name='he')
    permission_he = models.BooleanField(default=False)
    permission_me = models.BooleanField(default=False)

我需要的查询:

在djangos中获取各种user_he的用户表,其中user_me = 1并且具有permission_he = True且permission_me = True

这和其他几个查询都没有成功......

get_friends =  User.objects.values_list('username').filter(geoCatch__user_me=id)/
.filter(permission_he = True).filter(permission_me= True)

给我错误:

  

django.core.exceptions.FieldError:无法将关键字'geoCatch'解析为字段。

2 个答案:

答案 0 :(得分:2)

friends = GeoCatch.objects.filter(user_me=User.objects.get(pk=id)) \
                    .filter(permission_me=True) \
                    .filter(permission_he=True).user_he_set.all()

答案 1 :(得分:1)

# id is an id of a user object
get_friends =  User.objects.values_list('username', flat=True)\
    .filter(me__user_me__id=id, me__permission_he = True, me__permission_me= True)