[英]Django inheritance from models.CharField with choices gives error
I have two classes which are used in application logic. 我有两个在应用程序逻辑中使用的类。 One is called Direction and the other is called Compass.
一个叫做方向,另一个叫做指南针。 Direction is a member of Compass.
Direction是Compass的成员。 What I am trying to implement is a modelField that wraps the Direction class and that I can use as a member in the Compass model.
我试图实现的是一个包装了Direction类的modelField,并且可以用作Compass模型的成员。 The DirectionField class inherits from models.CharField and sets choices from the parent class.
DirectionField类继承自models.CharField并设置父类的选择。
I think that this is a nice design because I can use the DirectionField in many other classes and it's easy to maintain. 我认为这是一个不错的设计,因为我可以在许多其他类中使用DirectionField,并且易于维护。 However, I get an error when I save the Compass model in the Admin page in Django.
但是,将指南针模型保存在Django的“管理”页面中时出现错误。 The error is "Value is not a valid choice."
错误为“值不是有效选择”。
I use Python 2.7 and Django 1.4. 我使用Python 2.7和Django 1.4。
Could someone please review this issue and suggest what the problem is and how I could resolve it. 有人可以复查此问题,并提出问题所在以及如何解决。
Here is the source: 来源如下:
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
Error in the Admin page (or form view) that I get when I save Compass: 保存Compass时出现的“管理”页面(或表单视图)中的错误:
Value <src.bo.tgEnum.Direction instance at 0x03E97E18> is not a valid choice.
To pass field validation you need to add this functions to Direction class: 要通过字段验证,您需要将此函数添加到Direction类:
def __eq__(self, value):
return self.value == value
def __len__(self):
return len(self.value)
Because it compares value with choices keys and value has Dictionary type, key is string. 因为它比较值和选择键,并且值具有字典类型,所以键是字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.