2016-08-12 50 views
0

我想在創建所述用戶時創建一組屬於新用戶的「事件」對象。我想這樣做的方式是覆蓋Django的User類保存方法。在Django中爲新用戶創建單獨對象

我的用戶類只是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) 

對於我的事件類,我已經使用了Django的包叫做「MPTT 「:https://github.com/django-mptt/django-mptt/。這被選中了,因爲它是實現樹結構的一種簡單方法。該模型如下圖所示:

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... 

如何修正這個錯誤,或者想別的辦法做同樣的事情有什麼想法?有一兩件事我想的是,添加一個普通的方法到類樹說:

def tree(self): 
    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) 

但我不確定我會如何將其添加到管理員站點。

回答

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) 

pkid一般可以互換,因此,如果self.pk is None也意味着self.id is None

相關問題