2

I'm going to get mad now - I could not create a new Team-Instance. Django always displays the error: 'Team' instance needs to have a primary key value before a many-to-many relationship can be used.

Here's my model:

from django.contrib.auth.models import User
from django.db import models

class Team(models.Model):
    name = models.CharField(max_length=10)
    members = models.ManyToManyField(User)

    def save(self, *args, **kwargs):
        if self.pk:
            # for later use
            pass
        super(Team, self).save(*args, **kwargs)

Now I'd like to create a new Team...

from django.contrib.auth.models import User
from models import Team

user_obj = User.objects.get(pk=1)
new = Team()
new.name = 'aaa'
new.save()
new.members.add(user_obj)

Could someone see the mistake?

edit i've read the docs and this (very great) answer How to create an object for a Django model with a many to many field? - still can't figure out what is wrong

Community
  • 1
  • 1
Thomas Schwärzl
  • 9,518
  • 6
  • 43
  • 69
  • This code looks correct. Maybe the error is located elsewhere? Is this your whole code or is it truncated? Can you post a full stack trace? – Jingo Oct 16 '12 at 19:14
  • there's a custom save method - but it only calls the `super(Team, self)...`- here's the stacktrace: http://dpaste.com/814410/ – Thomas Schwärzl Oct 16 '12 at 19:16
  • The only way I could see this happening is that somehow your save() method is not committing to the database. Please include the code for your custom save() method. – drewman Oct 16 '12 at 19:22
  • updated question with save() method – Thomas Schwärzl Oct 16 '12 at 19:24

2 Answers2

1

Ahh, it is in your save() method. Try this fix:

def save(self, *args, **kwargs):
    obj = super(Team, self).save(*args, **kwargs)
    if obj.id:
        # for later use
        pass
    return obj
drewman
  • 1,565
  • 11
  • 15
1

@init3's accepted answer didn't work for me because obj kept resolving to 'NoneType', in other words, call to super didn't return anything. Got it working as:

def save(self, *args, **kwargs):
    super(Team, self).save(*args, **kwargs)
    if self.pk:
        pass
epylinkn
  • 1,128
  • 12
  • 16