我有一个看起来像这样的模型
class Connections(models.Model):
following = models.ForeignKey(
User, related_name='following'
)
followers = models.ForeignKey(
User, related_name='followers'
)
def __unicode__(self):
return u'%s, %s' % (self.following.username, self.followers.username)
class Meta:
unique_together = (('following', 'followers'), )
然后在TastyPie中我使用以下代码来提取以下用户
class ConnectionsResource(ModelResource):
user_following = fields.ForeignKey(UserResource, 'following')
user_follower = fields.ForeignKey(UserResource, 'followers')
class Meta:
queryset = Connections.objects.all()
resource_name = 'connections'
def prepend_urls(self):
return[
url(r"^(?P<resource_name>%s)%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('connections'), name="api_connections"),
]
def connections(self,request,**kwargs):
if request.user and request.user.is_authenticated():
#Scribble Comments
if request.GET.get('followers', ''):
user = request.user
followers = [connections.following for connections in user.followers.all()]
followers_count = 1
if followers_count > 0:
paginator = Paginator(followers, 20)
try:
page = paginator.page(int(request.GET.get('page', 1)))
except InvalidPage:
return self.create_response(request, { 'success': False, 'reason':'no more pages' })
objects = []
for result in page.object_list:
bundle = self.build_bundle(obj=result, request=request)
bundle = self.full_dehydrate(bundle)
objects.append(bundle)
followers_list = {
'followers_count': followers_count,
'followers' : objects,
'success': True,
}
self.log_throttled_access(request)
return self.create_response(request, followers_list)
else:
return self.create_response(request, { 'success': False, 'reason':'No Followers' })
else:
return self.create_response(request, { 'success': False, 'reason':'Wrong Query'})
else:
return self.create_response(request, { 'success': False, 'reason':'User not Logged in'})
def determine_format(self, request):
return 'application/json'
但我继续收到'RelatedManager' object has no attribute 'pk'
错误。我不知道为什么
回溯:
traceback: "Traceback (most recent call last):
File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 202, in wrapper response = callback(request, *args, **kwargs)
File "/Users/jonathan/virtualenvs/myproject/bin/django_worksquid/scribbler/api.py", line 547, in connections bundle = self.full_dehydrate(bundle)
File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 837, in full_dehydrate bundle.data[field_name] = field_object.dehydrate(bundle)
File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/fields.py", line 729, in dehydrate return self.dehydrate_related(fk_bundle, self.fk_resource)
File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/fields.py", line 557, in dehydrate_related return related_resource.get_resource_uri(bundle)
File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 784, in get_resource_uri return self._build_reverse_url(url_name, kwargs=self.resource_uri_kwargs(bundle_or_obj))
File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 763, in resource_uri_kwargs kwargs.update(self.detail_uri_kwargs(bundle_or_obj))
File "/Users/jonathan/virtualenvs/myproject/lib/python2.7/site-packages/tastypie/resources.py", line 2371, in detail_uri_kwargs kwargs[self._meta.detail_uri_name] = getattr(bundle_or_obj.obj, self._meta.detail_uri_name) AttributeError: 'RelatedManager' object has no attribute 'pk' "
当我将followers_count = 1
更改为followers_count = followers.count()
时,它会给我
"count() takes exactly one argument (0 given)" error
我终于意识到关注者是一个列表而不是一个对象,所以我将我的代码改为
def connections(self,request,**kwargs):
if request.user and request.user.is_authenticated():
#Scribble Comments
if request.GET.get('followers', ''):
user = request.user
followers = [connections.following for connections in user.followers.all()]
users_id = [s.id for s in followers]
users=User.objects.filter(id__in = users_id)
users_count = users.count()
users_list = {
'users_count': users_count,
'users' : users,
'success': True,
}
return self.create_response(request, users_list)
else:
return self.create_response(request, { 'success': False, 'reason':'Wrong Query'})
else:
return self.create_response(request, { 'success': False, 'reason':'User not Logged in'})
现在我得到了输出,但我从对象的角度来看,比如
success: true,
users: "[<User: abc>, <User: test>, <User: abc2>, <User: test2>]",
users_count: 4
而不是这个,我想让我的对象显示电子邮件地址和所有用户,而不仅仅是这个对象。
答案 0 :(得分:3)
解决方案很简单。事实证明,我应该使用ToManyField
用于非ForeignKey
的用户对象,并修复了所有内容!
答案 1 :(得分:0)
'RelatedManager' object has no attribute 'pk'
可能意味着TastyPie期待一个对象,但你给它一个RelatedManager
,就像connections.following
我要确保result
for result in page.object_list
是一个对象,您可能需要遍历所有connections.following
个用户。
for result in page.object_list:
print result
for following_user in result.all():
print following_user
bundle = self.build_bundle(obj=following_user, request=request)
bundle = self.full_dehydrate(bundle)
objects.append(bundle)
你也考虑过只使用ManyToMany field,也可以使用Profile
模型与用户建立OneToOne关系,或升级到允许extending the user model的Django 1.5?这样,您可以使用Django的内置功能,例如只说user.followers.all()
并获取跟随该用户的所有用户,而不是实现您自己的ManyToMany关系。
这样的东西可用于提取信息
users = [{
'email': u.email,
'name': u.name,
...
} for u in User.objects.filter(id__in = users_id)]
虽然你应该尝试使用build_bundle
users = [self.full_dehydrate(self.build_bundle(obj=u, request=request))
for u in User.objects.filter(id__in = users_id)]
答案 2 :(得分:0)
我可以在一个问题上提供帮助:
followers = [connections.following for connections in user.followers.all()]
您无法在此处调用.count()
,因为您将查询结果放入列表中。使用len(followers)
或User.objects.get(following__followers=user)
。
其余的代码很奇怪,但我也看不出它的确定问题。问题可能在UserResource
?你可能想看看第837行。