我想创建一组"事件"创建所述用户时属于新用户的对象。我想这样做的方法是覆盖Django的用户类保存方法。
我的User类只是Django用户类的扩展,有三个不同的选项来定义对象的类型:
bucket_selector
对于我的活动课程,我使用了名为" mptt":https://github.com/django-mptt/django-mptt/的Django软件包。这是选择的,因为它是实现树结构的简单方法。该模型如下所示:
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User, Group
from events.models import Event
class MyUser(models.Model):
user = models.OneToOneField(User, related_name='myuser', on_delete=models.CASCADE)
userID = models.CharField(max_length=30)
isA = models.BooleanField(default=False)
isB = models.BooleanField(default=False)
isC = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if self.pk is None and self.isA:
event = Event.objects.create(name="Event", rank="A", owner=self.user)
subEvent = Event.objects.create(name="Sub Event", rank="AA", owner=self.user, parent=event)
这样做,我收到以下错误:
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
class Event(MPTTModel):
name = models.CharField(max_length=30)
rank = models.CharField(max_length=10, null=True)
owner = models.ForeignKey(User, null=True, related_name='event', on_delete=models.CASCADE)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
class MPTTMeta:
order_indertion_by = ['rank']
def __unicode__(self):
return u'%s' % (self.name)
有关如何修复错误的任何想法,或想到另一种方法来做同样的事情?我想到的一件事是在课堂上添加常规方法说树:
ProgrammingError: column "owner_id" of relation "events_event" does not exist
LINE 1: INSERT INTO "events_event" ("name", "rank", "owner_id", "par...
但我不确定如何将其添加到管理网站。
答案 0 :(得分:0)
我的猜测是你在保存用户对象之前调用了代码。
如果你的类MyUser
实际上正在扩展Django用户模型(在你的代码中不是这样)你保存应该看起来像这样
def save(self, *args, **kwargs):
is_create = self.pk is None
user = super(MyUser, self).save(*args, **kwargs)
if is_create and self.isA:
event = Event.objects.create(name="Event", rank="A", owner=user)
subEvent = Event.objects.create(name="Sub Event", rank="AA", owner=user, parent=event)
pk
和id
通常可以互换,因此如果self.pk is None
也意味着self.id is None
。