我有简单的模型,用户有他们需要评价的文件。我使用 Django/tastypie。
[models.py]
class User( models.Model ):
[..]
class File( models.Model ):
[..]
bVerified = models.IntegerField(blank=True, null=True, )
class UserFile( models.Model ):
[..]
nRate = models.CharField( max_length=4)
user = models.ForeignKey( User, related_name="userfile" )
file = models.ForeignKey( File, related_name="userfile" )
[api.py]
class UserFileResource( MyModelResource ) :
user = fields.ToOneField( 'app.api.UserResource','user',full=True,null=True)
file = fields.ToOneField( 'app.api.FileResource','file',full=True,null=True)
class Meta:
queryset = UserFile.objects.all()
resource_name = 'userfile'
filtering = {
"id" : ALL,
"file" : ALL_WITH_RELATIONS,
"user" : ALL_WITH_RELATIONS,
}
def apply_filters(self, request, applicable_filters):
oBaseObject = super( UserFileResource, self ).apply_filters( request, applicable_filters )
loQ = []
idUser = str( request.user.id )
loQ.append( Q( **{ 'user__id__exact' : idUser } ) )
loQ.append( Q( **{ 'file__bVerified__exact' : 1 } ) )
oFilter = reduce( operator.and_, loQ )
oBaseObject = oBaseObject.filter( oFilter )
return oBaseObject
使用上面的代码,这是我目前得到的结果集,即我所有的(约翰的)文件:
{
"meta": { "limit": 10, "next": null, "offset": 0, "previous": null, "total_count": 3 },
"objects": [
{
"id": 1,
"nRate" : 5,
"file": { "name": "test1.txt", "bVerified": 1 },
"user": { "id": 1, "name": "john" }
},
{
"id": 2,
"nRate" : 3,
"file": { "name": "test2.txt", "bVerified": 1 },
"user": { "id": 1, "name": "john" }
},
{
"id": 3,
"nRate" : 4,
"file": { "name": "test3.txt", "bVerified": 1 },
"user": { "id": 1, "name": "john" }
}
]
}
我现在想对已定义的用户进行三个“集合论”查询。我(约翰)想将我的文件与其他两个用户(蒂姆和汤姆)进行比较
这些是我希望获得的三种查询的结果:
只有我(约翰)拥有的文件:
{
"meta": { "limit": 10, "next": null, "offset": 0, "previous": null, "total_count": 1 },
"objects": [
{
"id": 3,
"file": { "name": "test3.txt", "bVerified": 1 },
"user": [
{ "id": 2, "name": "john", "nRate" : 4 }
]
}
]
}
我(约翰)没有文件,但其他人(蒂姆和汤姆)有:
{
"meta": { "limit": 10, "next": null, "offset": 0, "previous": null, "total_count": 2 },
"objects": [
{
"id": 23,
"file": { "name": "test42.txt", "bVerified": 1 },
"user": [
{ "id": 2, "name": "tom", "nRate" : 7 },
{ "id": 3, "name": "tim", "nRate" : 7 }
]
},
{
"id": 24,
"file": { "name": "test43.txt", "bVerified": 1 },
"user": [
{ "id": 2, "name": "tom", "nRate" : 7 },
{ "id": 3, "name": "tim", "nRate" : 7 }
]
}
]
}
我们都有的文件:
{
"meta": { "limit": 10, "next": null, "offset": 0, "previous": null, "total_count": 1 },
"objects": [
{
"id": 1,
"file": { "name": "test1.txt", "bVerified": 1 },
"user": [
{ "id": 1, "name": "john", "nRate" : 5 },
{ "id": 2, "name": "tom", "nRate" : 4 },
{ "id": 3, "name": "tim", "nRate" : 7 }
]
}
]
}
有人已经做过这样的事情或者可以分享一些方法吗?