2010-10-28 34 views
1

下面的代碼是正在使用的管理員節省了貸款對象爲什麼貸款未定義時,類型(自我)工作得很好?

import uuid 

from django.db import models 
from django.contrib.auth.models import User 
from apps.partners.models import Agent 

# Create your models here. 
class Loan(models.Model): 
    """ This is our local info about the loan from the LOS """ 
    guid = models.CharField(max_length=64, blank=True) 
    number = models.CharField(max_length=64, blank=True) 
    name = models.CharField(max_length=64) 
    address = models.CharField(max_length=128) 
    address2 = models.CharField(max_length=128, null=True, blank=True) 
    city = models.CharField(max_length=32) 
    state = models.CharField(max_length=2) 
    zipcode = models.CharField(max_length=9) 
    borrowers = models.ManyToManyField(User, related_name='loan_borrowers') 
    officers = models.ManyToManyField(Agent, related_name='loan_officers') 

    def __unicode__(self): 
     return "%s %s, %s %s" % (self.address, self.city, self.state, self.zipcode) 

    def save(self, force_insert=False, force_update=False, using=None): 
     """ Adds a GUID if one is not present """ 
     if self.guid == None: 
      self.guid = uuid.uuid4().hex 
     super(Loan, self).save(force_insert, force_update, using) 

當我到了超線,我得到:

TypeError: super() argument 1 must be type, not None 

保存呼叫從options.py製成597行,在這一點obj被稱爲貸款對象。

如果我更換

super(type(self), self).save(force_insert, force_update, using) 

超()行一切都很好。這裏發生了什麼?

文件的其餘部分是:

class Need(models.Model): 
    from apps.public_portal.models import DocumentType 
    loan = models.ForeignKey(Loan, null=False, blank=False) 
    borrower = models.ForeignKey(User, null=False, blank=False) 
    doctype = models.ForeignKey(DocumentType, null=False, blank=False) 
    satisfied = models.DateTimeField(null=True, blank=True) 
    first_request = models.DateTimeField(auto_now_add=True) 
    last_request = models.DateTimeField(null=True, blank=True) 

    def __unicode__(self): 
     return "%s from %s for %s" % (self.doctype.name, self.borrower.get_full_name(), self.loan) 

所以我看不出任何有約束力的貸款爲無

回答

0

別的東西重新綁定LoanNone。往下看,或者在另一個模塊中。此外,你不希望type(self),因爲這將失敗的任何孫子或更進一步。

+0

我同意我不想要type(self),這是問題原因的一部分。我修改了問題以顯示整個文件。到底是怎麼回事? – boatcoder 2010-10-29 13:13:13

1

Django開發者提供了一個overriding the model save() method的模式。使用該模式,爲您節省()方法的實現應該是:

def save(self, *args, **kwargs): 
    if self.guid == None: 
     self.guid = uuid.uuid4().hex 
    super(Blog, self).save(*args, **kwargs) # Call the "real" save() method. 

讓我提供了不同的方法:使用signals

而不是嘗試覆蓋save()方法,使用pre-save signal初始化插入/更新記錄之前的guid字段。下面的代碼添加到您的model.py文件:

def add_loan_guid(sender, instance, **kwargs): 
    """Ensure that a Loan always has a guid""" 
    if instance.guid == None: 
     instance.guid = uuid.uuid4().hex 

pre_save.connect(add_loan_guid, sender=Loan) 

現在,一個貸款對象被保存的任何時間,但在此之前它被保存到數據庫,add_loan_guid()被調用,如果貸款實例沒有guid set,將會創建一個新的。

相關問題