class UserProfile(models.Model):
"""
Extending the Django User.
"""
user = models.OneToOneField(User,unique=True)
image_id = models.CharField(max_length=50,blank=True)
is_email_validated = models.BolleanField(default = False)
followers_count = models.IntegerField(max_length=5,default=0,blank=True,null=True)
following_users = ModelListField()
follower_users = ModelListField()
def __unicode__(self):
return u"%s" % self.user.first_name
def full_name(self):
return u"%s" % self.user.first_name + '' + self.user.last_name
def email(self):
return self.user.email
def username(self):
return self.user.username
def books_count(self):
return len(self.user.get_profile().books)
def create_user_profile(sender,instance,created,**kwargs):
if created:
UserProfile.objects.create(user=instance)
action.send(type="create_user",actor=instance,target=instance)
post_save.connect(create_user_profile,sender=User)
因此,我如何制作api呢?我是否要编写处理程序?(很混淆Django tastypie在这种情况下是如何工作的。)
我可以编写处理程序来返回api调用的数据,如GET / users // follow。但这是如何在tastypie中完成的吗?如果是,我如何将处理程序与API连接?
编辑: 这样的事情可以在django-piston中完成,如下所示:
from piston.handler import BaseHandler
from piston.utils import rc
from app.apps.user.models import User, UserProfile
class UserHandler(BaseHandler):
model = User
def read(self, request, user_id=None, action=None):
"""
GET /users/
following - GET /users/<user_id>/following
followers - GET /users/<user_id>/followers
user profile - GET /users/<user_id>/
"""
if action =="following":
return self.following(request, user_id)
elif action == "followers":
return self.followers(request, user_id)
else:
return self.get_user_profile(request, user_id)
def get_user_profile(self, request, user_id):
"""
User Profile
GET /users/<user_id>/
"""
user = User.objects.get(pk=user_id)
user_session = request.user
user_session_following = user_session.get_profile().following_users
if user.id in user_session_following:
follow_status=True
else:
follow_status=False
return user_actions.get_user_profile(user, follow_status)
答案 0 :(得分:1)
加入你的app / apps / user / api.py
from tastypie.resources import ModelResource
from django.contrib.auth.models import User
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
在你的urls.py中
from django.conf.urls.defaults import *
from app.apps.user.api import UserResource
v1_api = Api(api_name='v1') #api_name will be 'v1' in http://localhost:8000/v1/?format=json
v1_api.register(UserProfileResource())
urlpatterns = patterns('',
(r'^api/', include(v1_api.urls)),
)
我不是故意在这里粗暴,但阅读文档,特别是quickstart,会有所帮助。
你的api现在(在你的devserver中)暴露于
http://localhost:8000/api/v1/?format=json
多数民众赞成。您不必编写任何代码,例如
- retrieve all users in json:
http://localhost:8000/api/v1/user/?format=json
- retrieve the entry in the user table with the key 1
http://localhost:8000/api/v1/user/1/?format=json
- retrieve the meta information about your UserResource
http://localhost:8000/api/v1/user/schema/?format=json
希望这能帮到你!