我关注this articles每个字段有2列,所以我的自定义字段代码是这样的:
class GeopositionField(models.Field):
description = "A geoposition (latitude and longitude)"
def __init__(self, *args, **kwargs):
kwargs['max_length'] = 42
super(GeopositionField, self).__init__(*args, **kwargs)
def contribute_to_class(self, cls, name):
self.name = name
position_longitude = DecimalField(decimal_places=6,max_digits=9,default=0,blank=True)
cls.add_to_class("position_longitude",position_longitude)
position_latitude = DecimalField(decimal_places=6,max_digits=8,default=0,blank=True)
cls.add_to_class("position_latitude",position_latitude)
setattr(cls,"position_longitude",position_longitude)
setattr(cls,"position_latitude",position_latitude)
我的模型类是请求:
class Request(models.Model):
person = models.ForeignKey(Person)
position = GeopositionField(null = False,default = 0)
(我正在修改django-geoposition)到目前为止,我的表格中只有position_latitude和position_longitude(而不仅仅是原来的“位置”)
在
+--------------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| person_id | int(11) | NO | MUL | NULL | |
| creation_date | datetime | NO | | NULL | |
| position | varchar(50) | NO | | NULL | |
+--------------------+---------------+------+-----+---------+----------------+
在
+--------------------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+---------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| person_id | int(11) | NO | MUL | NULL | |
| creation_date | datetime | NO | | NULL | |
| position_longitude | decimal(9,6) | NO | | NULL | |
| position_latitude | decimal(8,6) | NO | | NULL | |
+--------------------+---------------+------+-----+---------+----------------+
这很好,但问题出现在django admin和shell中,因为如果我创建一个“Request”对象然后我尝试打印“position”属性,我得到一个错误,说“位置”属性不存在:
>>> from main.models import Request
>>> x = Request()
>>> x.position
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Request' object has no attribute 'position'
>>>
如果我在Request类的__init__
方法中设置位置属性,那就有效,但这不是主意。
所以,回到真正的问题,当我尝试在管理面板中显示它时,如果我明确地调用“位置”字段django会抛出错误,奇怪的是它适用于“position_latitude”和“position_longitude”
class RequestAdminForm(forms.ModelForm):
class Meta:
model = Request
# fields = ['position_latitude','position_longitude] <-- this works !
fields = ['position'] # <-- this returns error = Unknown field(s) (position) specified for Request
当RequestAdminForm在字段列表中只有“位置”时,有没有办法显示“position_latitude”和“position_longitude”?这就是我想要实现的目标。为什么会发生“未定义属性”问题?