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 美味派是如何工作的很困惑。)
我可以编写处理程序来为 GET /users//following 之类的 api 调用返回数据。但这就是美味派的做法吗?如果是,我如何将处理程序与 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)