我想创建一个模型类" Event" (事件将是两个类型one_time_event和recurring_event),并且两个" one_time_event"的单独模型类。和" recurring_event"。
所以在表格Event中,我希望有类似的东西
event_id event_type(2choices) event_type_id
---------------------------------------------------------------------------
1 one_time_event one_time_event_Object
2 recurring_event recurring_event_object
3 one_time_event one_time_event_Object
4 recurring_event recurring_event_object
所以问题是如何定义我的模型类来实现这一目标。
提前致谢
答案 0 :(得分:0)
您正在寻找contenttypes
投稿应用中提供的GenericForeignKey
。
简而言之,您将创建一个可以指向不同模型的键:
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class OneTimeEvent(models.Model):
# your normal fields here
class RecurringEvent(models.Model):
# your normal fields here
class Event(models.Model):
# your normal fields here
content_type = models.ForeignKey(ContentType) # A link to any kind of content
object_id = models.PositiveIntegerField() # The id for the linked object
event_type = models.GenericForeignKey() # This can point to any kind of object
现在,你可以这样做:
recurring_event = RecurringEvent.objects.create()
event = Event()
event.event_type = recurring_event
event.save()