问题
I have a Model structure that keeps track of following and followers of a User.
class Connections(models.Model):
following = models.ForeignKey(
User, related_name='following'
)
followers = models.ForeignKey(
User, related_name='followers'
)
class Meta:
unique_together = (('following', 'followers'), )
Post models
class Post(models.Model):
body = models.TextField()
user = models.ForeignKey(User)
#media = models.ForeignKey(postMedia)
post_image = models.ImageField(upload_to=get_postimage_path)
type_of_post = models.CharField(max_length=20)
def __unicode__(self):
return u'%s, %s' % (self.user.username, self.body)
class Sharedpost(models.Model):
post = models.ForeignKey(post, unique=True)
date = models.DateTimeField(auto_now_add=True)
favors = models.IntegerField(default=1)
users_favored = models.ManyToManyField(User, related_name='users_favored')
notify_users = models.ManyToManyField(User, related_name='notify_users')
def __unicode__(self):
return u'%s, %s, %s' % (self.post.user.username, self.post.body, self.pk)
Now if I have to fetch following for a user I do something like this in my views
following = [connections.followers for connections in user.following.all()]
Now I am trying to design an API for my web application using Tasypie, I am not sure how to represent this relationship in my ModelResources.
I want to generate a list of followers and following in it, and then use that as my filter as well to extract all the posts made my the people the user is following.
curl http://localhost:8000/api/v1/sharedpost/?post__user__username=abc
This is what I am using to filter out all the posts made by a specific user, but I want a filter for all the following users.
I can probably use
def get_object_list(self, request):
return super(SharedPostResource, self).get_object_list(request).filter(post__user=request.user)
and then
def get_object_list(self, request):
user=request.user
following = [connections.followers for connections in user.following.all()]
return super(SharedPostResource,self).get_object_list(request).filter(post__user__in=following).order_by('-date')
but wont I have to make different resources for all of this then? is there a better way than that? in which maybe I can make one Resource more versatile?
来源:https://stackoverflow.com/questions/14818962/how-to-represent-unique-together-in-tastypie