我有两个带有外键-user的关系表。返回给我的查询集如下
city: null,
contact_address: "",
contact_number: "9874563210",
country: null,
date_of_birth: null,
id: 12,
invitation_text: "Aphabets",
middle_name: "def",
profile_img: null,
resource_uri: "/client/api/v1/profile/12/",
state: null,
user: {
date_joined: "2014-07-27T04:07:00",
email: "abc@cba.com",
first_name: "abc",
id: 24,
is_active: false,
last_login: "2014-07-27T04:07:00",
last_name: "ghi",
resource_uri: "/client/api/v1/user/24/",
username: "abc@cba.com"
},
zipcode: n
我的api资源如下:
class ProfileResource(ModelResource):
user = fields.ToOneField(UserResource,'user', full=True)
"""docstring for ProfileResource"""
def alter_list_data_to_serialize(self, request, data):
if request.GET.get('meta_only'):
return {'meta': data['meta']}
return data
def authorized_read_list(self, object_list, bundle):
if (bundle.request.user.is_superuser is True) or (bundle.request.is_staff is True) :
return object_list.all().select_related()
else:
return object_list.filter(user=bundle.request.user).select_related()
def obj_create(self, bundle, **kwargs):
return super(ProfileResource, self).obj_create(bundle, user=bundle.request.user)
class Meta:
queryset = UserProfile.objects.filter()
resource_name = 'profile'
default_format = 'application/json'
list_allowed_methods = ['get','post']
detail_allowed_methods = ['get', 'post', 'put', 'delete', 'patch']
serializer = Serializer()
default_format = 'application/json'
authentication = Authentication()
authorization = DjangoAuthorization()
always_return_data = True
我需要过滤查询集,以便只返回活动用户,就像过滤器一样。
当我尝试object_list.filter(is_active = true)时。我收到一条错误说" is_active"不是一个有效的选项,选项是' city',' country' ..等。如何在过滤器中引用关系表值?
我看到过覆盖apply_filter方法的建议..但我的问题是..是不是有办法过滤使用外键值?
请指导我完成本节。提前致谢。
答案 0 :(得分:2)
尝试:
object_list.filter(user__is_active = true)
您可以在此处找到相关文档:https://docs.djangoproject.com/en/1.6/topics/db/queries/#lookups-that-span-relationships