How to represent unique together in Tastypie

99封情书 提交于 2020-01-25 07:35:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!