2013-02-01 124 views
3

我對Django來說很新,這讓我很難過。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

你構建模型的方式是錯誤的。您不需要放置主鍵,因爲django會自動生成它 – catherine

回答

3

如果你看看你的數據庫中的外鍵是一個整數值!但監守Django的的ORM,你可以在對象的條件,而不是數字

互動通過event_id

e.event_pid.event_id

2

您可以訪問ID來獲得ForeignKey的的整數,你應該能夠訪問它通過查看e.event_pid.event_id,您的視圖中的RecurrenceEvent。

但我認爲你錯誤的模型的領域。

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將是您的視圖/模板中需要的整數。