Modelmanager没有覆盖保存方法

时间:2015-12-16 17:24:34

标签: django django-models

这是我的模特和模特经理。我基本上想要覆盖save方法,所以我可以在保存Companymanager之前执行一些操作。

我已经定义了一个模型管理器,但是在我尝试保存公司对象时没有调用它的保存方法。

class CompanyManager(models.Manager):
    """
    Custom model manager to return a random scenario
    """
    def save(self, *args, **kwargs):
        #User.objects.create()
        #print '*args == ', *args
        #print '*kwargs == ', *kwargs
        #User.objects.filter()
        for each in args:
            print 'each=',each



class Company(models.Model):

    objects =CompanyManager()

    COMPANY_SIZE = (
    ('1-10', '1-10'),
    ('11-50', '11-50'),
    ('51-200', '51-200'),
    ('201-500', '200-500'),
    ('501-1000', '501-1000'),
    ('1001-5000', '1001-5000'),
    ('5001-10000', '5001-10000'),
    ('10000+', '10000+'),
    )   

    INDUSTRY = (
        ('Telecom','Telecom'),
        ('Technology','Technology')
        )

    users = models.ManyToManyField(User)
    description = models.CharField(max_length=500,default='')
    size = models.CharField(max_length=10,choices=COMPANY_SIZE,default='1-10')
    industry = models.CharField(max_length=100,choices=INDUSTRY,default='---')
    url = models.URLField(max_length=200,default='')
    logo = models.ImageField(upload_to='company',default='')
    addr1 = models.CharField(max_length=200,default='')
    addr2 = models.CharField(max_length=200,default='')
    city = models.CharField(max_length=200,default='')
    state = models.CharField(max_length=2,choices=STATE_CHOICES,default='')
    zip_cd = models.CharField(max_length=5,default='')
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number_1 = models.CharField(validators=[phone_regex], blank=True,max_length=15)
    phone_number_2 = models.CharField(validators=[phone_regex], blank=True,max_length=15)


    def __str__(self):
        return self.name

2 个答案:

答案 0 :(得分:4)

save()是模型实例方法,而不是管理器方法。您需要将其移动到您的模型:

class Company(models.Model):
    def save(self, *args, **kwargs):
        #User.objects.create()
        #print '*args == ', *args
        #print '*kwargs == ', *kwargs
        #User.objects.filter()
        for each in args:
            print 'each=',each

    ...

答案 1 :(得分:0)

让sharedintance = modelmanagar()

class modelmanagar:NSObject {

var database : FMDatabase? = nil

class func getinstance() -> modelmanagar
{
    if(sharedintance.database == nil)
    {

        let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

        let fileURL = documentURL.appendingPathComponent("dddddbbbbbb.sqlite" as String)

        sharedintance.database = FMDatabase(path:fileURL.path)
    }

    return sharedintance
}