我是Django的新手,这让我很难过。
我正在开发一个调度工具,到目前为止有两个模型:
#----------------------------------------------------------------------------------
class ReccurenceEvent(models.Model):
"""
A recurrence event defined an event which recurses over a period of time. The pattern of the recursion
is defined within the rec_type attribute.
"""
event_id = models.IntegerField(primary_key=True)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
text = models.CharField(max_length=30)
rec_type = models.CharField(max_length=32)
event_length = models.BigIntegerField(null=True)
#----------------------------------------------------------------------------------
class Event(models.Model):
"""
A an event represents an independent calender event.
If the event relates to a series, the p_id points to a particular ReccurencePattern
"""
event_id = models.IntegerField(primary_key=True)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
text = models.CharField(max_length=30)
rec_type = models.CharField(max_length=32)
event_length = models.BigIntegerField(null=True)
event_pid = models.ForeignKey(ReccurenceEvent, null=True)
在某些情况下,我想将一个父事件id(event_pid)分配给一个事件,但这应该是一个整数值,而不是对该对象的引用。
当我执行以下操作时:
e.event_pid = event_pid
我收到以下消息:
Cannot assign "u'1359741862566'": "Event.event_pid" must be a "ReccurenceEvent" instance.
好的,但是如果提供一个重复实例:
e.event_pid = ReccurenceEvent.objects.get(event_id = event_pid)
我没有在响应中存储我需要的整数值。
有人可以指出我哪里出错吗?
答案 0 :(得分:3)
如果查看数据库,外键是一个整数值!但是因为你可以根据对象而不是数字来互动django orm
要获取ForeignKey的整数,您应该可以通过event_id
e.event_pid.event_id
答案 1 :(得分:2)
您可以通过查看e.event_pid.event_id来访问视图中的RecurrenceEvent的id。
但我认为你错误地模仿了你模特的领域。
class ReccurenceEvent(models.Model):
event_id = models.IntegerField(primary_key=True)
start_date = models.DateTimeField()
end_date = models.DateTimeField()
text = models.CharField(max_length=30)
rec_type = models.CharField(max_length=32)
event_length = models.BigIntegerField(null=True)
class Event(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
text = models.CharField(max_length=30)
rec_type = models.CharField(max_length=32)
event_length = models.BigIntegerField(null=True)
reccurance = models.ForeignKey(ReccurenceEvent, null=True)
然后,您只需通过该事件访问RecurranceEvent的属性。此外,您不需要显式添加主键。 Django为你做到了。它位于.id
和.pk
。
所以e.reccurance.id
将是您在视图/模板中需要的整数。