Instantiate model instance with manytomany field in Django

I have a method that works, but it seems very clumsy, and I would think there is a better way to do this.

I have a Model that relates a user on my site (a twitter clone for learning purposes) to a list of other users.

Right now when I create a new user, I want to initialize that list with the user as a member of the list.

My model is:

class FollowerList(models.Model)
    follower = models.ForeignKey(User,related_name="follower")
    followed = models.ManyToManyField(User,related_name="followed")

The code in my view that I'm using right now is

user = User.objects.get(username=uname)
flst = FollowerList()
flst.follower = user
flst.save()
flst.followed.add(user)
flst.save()

It seems to me like there should be a method for creating this without calling save() twice, but I can't seem to find it in the docs or anywhere else.

12
задан Daniel Holmes 29 July 2019 в 14:03
поделиться