当类型(自我)工作正常时,为什么贷款未定义?

时间:2010-10-28 22:05:18

标签: python django django-models django-admin

管理员使用以下代码保存贷款对象

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被称为Loan对象。

如果我用

替换super()行
    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)

所以我看不出有什么东西将贷款绑定到无

2 个答案:

答案 0 :(得分:1)

Django开发人员为overriding the model save() method提供了一种模式。使用该模式,save()方法的实现应该是:

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

在插入/更新记录之前,使用pre-save signal初始化guid字段,而不是尝试覆盖save()方法。将以下代码添加到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 )

现在,无论何时保存Loan对象,但在将其保存到数据库之前,都会调用add_loan_guid(),如果Loan实例没有设置guid,则会创建一个新的。

答案 1 :(得分:0)

还有其他东西将Loan重新绑定到None。向下看,或者在另一个模块中。此外,您不希望type(self),因为对于任何孙子女或其他孙女都会失败。