Home > Software design >  Django ORM better way to manipulate django ORM query to find related data
Django ORM better way to manipulate django ORM query to find related data

Time:11-23

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)

CodePudding user response:

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.

  • Related