Django foreign key setting
I'm new to Django and this puzzled me.
I am working on a planning tool and have two models:
#----------------------------------------------------------------------------------
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)
In certain circumstances, I want to assign a parent event ID (event_pid) to an event, but it must be an integer value and not an object reference.
When I do the following:
e.event_pid = event_pid
I receive the following message:
Cannot assign "u'1359741862566'": "Event.event_pid" must be a "ReccurenceEvent" instance.
Ok, but if a provide an instance of repetition with:
e.event_pid = ReccurenceEvent.objects.get(event_id = event_pid)
I am not storing the integer value that I need in the response.
Can anyone point out where I am going wrong?
source to share
You can access the RecurrenceEvent id in your view by looking at e.event_pid.event_id.
But I think you are using the fields of your model incorrectly.
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)
Then you just access the RecurranceEvent attributes through the event. Also, you don't need to explicitly add the primary key. Django does it for you. It is available in .id
and .pk
.
so it e.reccurance.id
will be the integer you need in your view / template.
source to share