1

Models:

class Tweets(models.Model):

    date_created = models.DateTimeField(default=now, verbose_name="Created on")
    tweet_data = models.TextField(verbose_name='tweet message')
    user = models.ForeignKey(User,on_delete=DO_NOTHING)

class UserFollowers(models.Model):

    follower_user = models.ForeignKey(User,on_delete=CASCADE,related_name="follower")
    followee_user = models.ForeignKey(User,on_delete=CASCADE,related_name="followee")

The UserFollowers table has record for who follows whom.

Here, I need to get all tweets posted by people I follow

Current approach:

        myfollowees = UserFollowers.objects.filter(follower_user=user_idx)
        print(myfollowees)
        myfolloweeslist = []
        for ele in myfollowees:
            myfolloweeslist.append(ele.followee_user.id)
        my_timeline_tweets = Tweets.objects.filter(user_id__in = myfolloweeslist)
  1. generate the my followee list (list of people I follow)
  2. fetch tweets where tweet is posted by userid and is also present in myfolloweelist

I would like to know if there is a better way to handle this.

I tried this and it worked for just one value of user_idx but not for others:

        my_timeline_tweets = Tweets.objects.filter(user__follower = user_idx)

1 Answer 1

1

You can filter with:

Tweet.objects.filter(user__followee__follower_user=user_idx)

This will retrieve the Tweets for which the .user is a User object for which a UserFollowers object exists with the .user of the Tweet as followee_user, and as follower_user the user_idx.


Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for your help. Is there any resource to read about how to write the relationships about ORM filtering.
@akashdeep: perhaps you can follow the making queries section of the documentation. This is explains quite well how to make more advanced queries. It might also help to write these queries in the shell and thus experiment with the discussed techniques.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.