Django自定义字段具有多重继承

时间:2011-04-02 16:04:26

标签: python django multiple-inheritance custom-fields

我有两个自定义Django字段,JSONFieldCompressedField,两者都运行良好。我想也有一个CompressedJSONField,而我更希望能做到这一点:

class CompressedJSONField(JSONField, CompressedField):
    pass

但在导入时我得到:

RuntimeError: maximum recursion depth exceeded while calling a Python object

我可以在Django中找到有关使用具有多重继承的模型的信息,但没有关于对字段执行相同操作的信息。这有可能吗?或者我应该在这个阶段放弃?

修改

为了清楚起见,我不认为这与我的代码的细节有关,因为下面的代码有完全相同的问题:

class CustomField(models.TextField, models.CharField):
    pass

编辑2:

我目前正在使用Python 2.6.6和Django 1.3。这是我的剥离右下测试示例的完整代码:

customfields.py

from django.db import models


class CompressedField(models.TextField):
    """ Standard TextField with automatic compression/decompression. """

    __metaclass__ = models.SubfieldBase
    description = 'Field which compresses stored data.'

    def to_python(self, value):
        return value

    def get_db_prep_value(self, value, **kwargs):
        return super(CompressedField, self)\
                        .get_db_prep_value(value, prepared=True)


class JSONField(models.TextField):
    """ JSONField with automatic serialization/deserialization. """

    __metaclass__ = models.SubfieldBase
    description = 'Field which stores a JSON object'

    def to_python(self, value):
        return value

    def get_db_prep_save(self, value, **kwargs):
        return super(JSONField, self).get_db_prep_save(value, **kwargs)


class CompressedJSONField(JSONField, CompressedField):
    pass

models.py

from django.db import models
from customfields import CompressedField, JSONField, CompressedJSONField

class TestModel(models.Model):

    name = models.CharField(max_length=150)
    compressed_field = CompressedField()
    json_field = JSONField()
    compressed_json_field = CompressedJSONField()

    def __unicode__(self):
        return self.name

当我添加compressed_json_field = CompressedJSONField()行时,我在初始化Django时遇到错误。

2 个答案:

答案 0 :(得分:2)

在做了一些快速测试之后,我发现如果你从JSON和压缩字段中删除元类并将它放在compressedJSON字段中,它就会编译。如果你需要JSON或压缩字段然后继承它们并且jusst添加__metaclass__ = models.SubfieldBase

我不得不承认我没有做过任何繁重的测试:

from django.db import models                                                       


class CompressedField(models.TextField):                                           
    """ Standard TextField with automatic compression/decompression. """           

    description = 'Field which compresses stored data.'                            

    def to_python(self, value):                                                    
        return value                                                               

    def get_db_prep_value(self, value, **kwargs):                                  
        return super(CompressedField, self).get_db_prep_value(value, prepared=True)


class JSONField(models.TextField):                                                 
    """ JSONField with automatic serialization/deserialization. """                

    description = 'Field which stores a JSON object'                               

    def to_python(self, value):                                                    
        return value 

    def get_db_prep_save(self, value, **kwargs):                                   
        return super(JSONField, self).get_db_prep_save(value, **kwargs)            


class CompressedJSONField(JSONField, CompressedField):                             
    __metaclass__ = models.SubfieldBase                                            

class TestModel(models.Model):                                                     

    name = models.CharField(max_length=150)                                        
    #compressed_field = CompressedField()                                          
    #json_field = JSONField()                                                      
    compressed_json_field = CompressedJSONField()                                  

    def __unicode__(self):                                                         
        return self.name

如果你想分别使用JSON和Commpressed字段,我认为这个想法会起作用:

class JSONFieldSubClass(JSONField):
    __metaclass__ = models.SubfieldBase

老实说......我真的不明白这一点。

编辑基础方法破解

class CompressedJSONField(JSONField, CompressedField):
    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        value = JSONField.to_python(self, value)
        value = CompressedField.to_python(self, value)
        return value

另一种方法是让类上的to_python()具有唯一的名称,并在继承的类中调用它们to_python()方法

或者查看此answer

修改 在一些阅读之后,如果你在第一个基地to_python()中实现对super(class, self).method(args)的调用,那么它将调用第二个基数。如果你使用超级一致,那么你应该没有任何问题。 http://docs.python.org/library/functions.html#super值得一试,http://www.artima.com/weblogs/viewpost.jsp?thread=237121

class base1(object):                                                               
    def name(self, value):                                                         
        print "base1", value                                                       
        super(base1, self).name(value)                                             

    def to_python(self, value):                                                    
        value = value + " base 1 "                                                 
        if(hasattr(super(base1, self), "to_python")):                              
            value = super(base1, self).to_python(value)                            
        return value                                                               

class base2(object):                                                               
    def name(self, value):                                                         
        print "base2", value                                                       

    def to_python(self, value):                                                    
        value = value + " base 2 "                                                 
        if(hasattr(super(base2, self), "to_python")):                              
            value = super(base2, self).to_python(value)                            
        return value                                                               

class superClass(base1, base2):                                                    
    def name(self, value):                                                         
        super(superClass, self).name(value)                                        
        print "super Class", value    

答案 1 :(得分:-2)

很难理解您何时收到该错误。但是看看DJango代码,有类似的实现(多重继承)

参考:类ImageFieldFile(ImageFile,FieldFile)
在django / db / models / fields