4

我对 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)

我没有在响应中存储我需要的整数值。

有人能指出我哪里出错了吗?

4

2 回答 2

3

如果你查看你的数据库,外键是一个整数值!但是由于 django orm,您可以根据对象而不是数字进行交互

要获取 ForeignKey 的整数,您应该能够通过它访问它event_id

e.event_pid.event_id

于 2013-02-01T18:23:45.883 回答
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您的视图/模板中需要的整数也是如此。

于 2013-02-01T18:24:52.073 回答