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

时间:2012-01-26 08:30:24

标签: django django-registration

我已经更改了django注册码。我在注册期间在UserProfileBusiness模型中插入数据。 数据正在UserProfile模型中保存。

#TODO: saving contact and address field data into UserProfile
user_profile = new_user.get_profile()
user_profile.user = new_user
user_profile.contact, user_profile.address = contact, kwargs['address']
user_profile.save()

以下代码无效。获取此错误。 'Business' instance needs to have a primary key value before a many-to-many relationship can be used.

#TODO: saving business field data into Business Model
user_business = Business()
user_business.owner = new_user
user_business.name = business
user_business.save()

感谢 更新

class Business(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
owner = models.ManyToManyField(User)
created = models.DateTimeField(editable=False, default=datetime.now)
modified = models.DateTimeField(editable=False, default=datetime.now)

class Meta:
    ordering = ['name']

def save(self):
    self.modified = datetime.now()
    if not self.slug:
        self.slug = slugify(self.name, instance=self)
    super(Business, self).save()

1 个答案:

答案 0 :(得分:1)

尝试将自定义代码更新为:

def save(self, *args, **kwargs):
    self.modified = datetime.now()
    if not self.slug:
        self.slug = slugify(self.name)
    super(Business, self).save(*args, **kwargs)

<强>更新

@no_access我认为将User实例分配到ManyToManyField中的Business的过程中存在问题。我怀疑ManyToManyField字段没有获得对正在创建的User实例的引用。 intermediate字段的ManyToManyField表需要一个适当的User对象来引用。所以,我认为这就是问题所在。