簡體   English   中英

Django從models.CharField繼承而來的錯誤

[英]Django inheritance from models.CharField with choices gives error

我有兩個在應用程序邏輯中使用的類。 一個叫做方向,另一個叫做指南針。 Direction是Compass的成員。 我試圖實現的是一個包裝了Direction類的modelField,並且可以用作Compass模型的成員。 DirectionField類繼承自models.CharField並設置父類的選擇。

我認為這是一個不錯的設計,因為我可以在許多其他類中使用DirectionField,並且易於維護。 但是,將指南針模型保存在Django的“管理”頁面中時出現錯誤。 錯誤為“值不是有效選擇”。

我使用Python 2.7和Django 1.4。

有人可以復查此問題,並提出問題所在以及如何解決。

來源如下:

class Direction():
    choices = (('N','North'),
               ('S','South'),
               ('E','East'),
               ('W','West'),)

    def __init__(self, value=None):
        self.value = value

class DirectionField(models.CharField):

    def __init__(self, *args, **kwargs):
        super(DirectionField, self).__init__(choices=Direction.choices,
                                             *args, **kwargs)

    __metaclass__ = models.SubfieldBase

    def to_python(self, value):
        if isinstance(value, Direction) or value is None:
            return value
        return Direction(value)

    def get_prep_value(self, value):
        return value.value

class Compass(models.Model):
    name = models.CharField(max_length=20)
    direction = modelFields.DirectionField(max_length=10)
    class Meta:
        db_table = 'campass'
    def __unicode__(self):
        return "%s/%s" % (self.name, self.direction)    

class CompassForm(forms.ModelForm):
    class Meta:
        model = Compass
    def clean(self):
        return self.cleaned_data

保存Compass時出現的“管理”頁面(或表單視圖)中的錯誤:

Value <src.bo.tgEnum.Direction instance at 0x03E97E18> is not a valid choice.

要通過字段驗證,您需要將此函數添加到Direction類:

def __eq__(self, value):
    return self.value == value

def __len__(self):
    return len(self.value)

因為它比較值和選擇鍵,並且值具有字典類型,所以鍵是字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM