13

I want to insert some data into a many to many field. I 'm getting this Error

user is an invalid keyword argument for this function

i also tried it with the relatedName...but still is not working...

My model looks like this:

models.py

class Workspace(models.Model):
    user = models.ManyToManyField(User,null=False, blank=False, related_name='members')
    workspace_name = models.CharField(max_length=80, null=False, blank=False)
    workspace_cat =models.CharField(max_length=80, null=True, blank=True)

views.py

db= Workspace(user=5, workspace_name=data_to_db['workspace_name'],workspace_cat=data_to_db['workspace_category'])
db.save()

Does somebody has an idea? Thanks a lot!

Jurudocs
  • 8,595
  • 19
  • 64
  • 88

1 Answers1

23

You used a ManyToMany field for the user field of your Workspace object, you can't give it one user, that's not how a ManyToMany works, that would be a ForeignKey.

Basically, using a ForeignKey, each workspace has one User associated to it, there's a direct link Workspace -> User, so it makes sense to create a Workspace and pass it an User, like you would be filling in a CharField.

A ManyToMany relationship means that several users can be associated to a Workspace and several Workspaces to one User. When using a ManyToMany, you would create your Workspace and then add some Users to it.

To add to a ManyToMany relationship, do the following:

my_user = User.objects.get(pk = 5)
my_workspace = Workspace(workspace_name=data_to_db['workspace_name'],workspace_cat=data_to_db['workspace_category'])
my_workspace.save() # committing to the DB first is necessary for M2M (Jurudocs edit)
my_workspace.users.add(my_user)

You should rename the user field to users to make the relationship name clearer.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
  • thanks for your answer... im my case i really want to have several users be associated to a Workspace and several Workspaces to one User ;-P – Jurudocs Oct 06 '12 at 22:23
  • @Jurudocs Then a `ManyToMany` is the appropriate use, please see my edited answer as to how to use it! – Thomas Orozco Oct 06 '12 at 22:25