在可以使用多对多关系之前,实例需要具有主键值

时间:2012-10-16 19:08:33

标签: django django-models django-orm

我现在要生气了 - 我无法创建一个新的Team-Instance。 Django始终显示错误:'Team' instance needs to have a primary key value before a many-to-many relationship can be used.

这是我的模特:

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)

现在我想创建一个新的团队......

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)

有人能看到错误吗?

修改 我已经阅读了文档和这个(非常好的)答案How to create an object for a Django model with a many to many field? - 仍然无法弄清楚出了什么问题

2 个答案:

答案 0 :(得分:1)

啊,它在你的save()方法中。试试这个修复:

def save(self, *args, **kwargs):
    obj = super(Team, self).save(*args, **kwargs)
    if obj.id:
        # for later use
        pass
    return obj

答案 1 :(得分:1)

@ init3接受的答案对我不起作用,因为obj一直解析为'NoneType',换句话说,调用super并没有返回任何内容。得到它的工作:

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