Question

I am trying to create a request(in django) that will return an array of posts(only user's posts, which the current user in following). Here are my models

Posts:

class Post(models.Model):
      title = models.CharField("Headline", max_length=100)
      body = models.TextField(max_length=1000)
      user_id = models.ForeignKey(User)
      thumbnail = models.FileField(upload_to=get_upload_file_name, blank=True)
      timestamp = models.DateTimeField(auto_now_add=True)

Following/followers:

class FollowUser(models.Model):
      who_id = models.IntegerField()
      whom_id = models.IntegerField()
      timestamp = models.DateTimeField(auto_now_add=True)

Users:

class UserProfile(models.Model):
      user = models.OneToOneField(User, unique=True)
      profile_pic = models.FileField(upload_to=get_upload_file_u_name, default='default.png', blank=True)
      bio = models.TextField(null=True)
      website = models.CharField(blank=True, max_length=100)
      location = models.CharField(blank=True, max_length=100)

      def __unicode__(self):
           return "%s's profile" % self.user

SQL request that I've created:

     SELECT *  FROM POSTS Where user_id IN (select whom_id from FOLLOWERS Where user_id = 1 )

So, I've tried to translate this sql code to django-like but I wasn't able. The main problem is that i can't request for an array.

Need help! Thanks

Was it helpful?

Solution

Try this

Post.objects.filter(user_id__in=FollowUser.objects.filter(who_id=1).values_list('whom_id'))

You can use this in your views.py by using the request parameter

Post.objects.filter(user_id__in=FollowUser.objects.filter(who_id=request.user.id).values_list('whom_id'))

OTHER TIPS

Table names are automatically generated by combining the name of the app and the lowercase name of the model. Try to use <appname>_posts

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top