Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 493
Matt Phillips Avatar asked Dec 23 '10 04:12

Matt Phillips


2 Answers

You don't need to call save after the many2many.add()

You could also shorten the code to 2 lines:

flst = FollowerList.objects.create(follower=user)
flst.followed.add(user)
like image 152
Yuji 'Tomita' Tomita Avatar answered Nov 16 '22 01:11

Yuji 'Tomita' Tomita


Yuji's answer is correct. You can not add an object to a M2M field until it has been saved. I wanted to mention a shorter way to create instances though.

user = User.objects.get(username=uname)
flst = FollowerList(follower=user) #use key word args to assign fields
flst.save()
flst.followed.add(user)
# don't need to save after adding an object to many to many field.

I find that syntax slightly nicer than creating an empty instance and assigning fields. Though the objects.create() method (mentioned by Yuki) is nicer still.

like image 24
Josh Smeaton Avatar answered Nov 16 '22 02:11

Josh Smeaton