Django - 将具有不同外键的Approval子类组合到一个类中

时间:2011-02-02 18:15:10

标签: django django-models

假设我的Django项目中有两个模型。

class Project(models.Model):
    name = models.CharField(max_length=256)

class Forecast(models.Model):
    name = models.CharField(max_length=256)
    project = models.ForeignKey(Project)

我想在一个独立的应用程序中构建一个Approval模型,允许我组合以下两个批准子类:

class ProjectApproval(models.Model):
    approver = models.ForeignKey(User)
    approved_object = models.ForeignKey(Project)

class ForecastApproval(models.Model):
    approver = models.ForeignKey(User)
    approved_object = models.ForeignKey(Forecast)

更像通用的东西:

class Approval(models.Model):
    user = models.ForeignKey(User)
    approved_object = [whatever I want ... a Project, a Forecast, a Checkbook, a Plan]

这可能吗?

谢谢,

麦克

1 个答案:

答案 0 :(得分:1)

当然可以,Django有通用关系:)

查看django文档here

实施的一个例子如下:

from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType  

class Approval(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')