1

Intro: Lets say I have a Feeds model which has a user and followers. When a user writes a post. All his followers get a feed on their homepage that the person they are following wrote a post.

class Feed(models.Model):
    being_followed = models.ForeignKey(User, blank=True, null=True, related_name="feeds_for_followers")
    follower = models.ManyToManyField(User, blank=True, related_name="homepage_feeds")        
    being_followed_post = models.ForeignKey(Post, blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)

My issue: Now if you see the post_create view below. The user is request.user the post is the post. However I am adding followers with the code

users_followers = post_user.followers.all()
for follower in users_followers: 
    feed.follower.add(follower) 

which is very inefficient. Is there a way I can add the entire queryset users_followers to the followers ManytoManyField

I tried

followers = user.followers.all()
feed.follower.add(followers)

I get the below error

int() argument must be a string, a bytes-like object or a number, not 'QuerySet'

Samir Tendulkar
  • 1,151
  • 3
  • 19
  • 47

1 Answers1

2

You can do it like this:

users_followers = post_user.followers.all()
feed.follower.add(*users_followers) 
ruddra
  • 50,746
  • 7
  • 78
  • 101