2013-06-04 13 views
3

我有以下情况。Django可链接FK的可重用应用程序?

我称之为“联系人”与它现有的应用程序的模型我有

我想创建一个名为“退订”新的应用程序,我希望把它可重用

这是我的问题:

在所谓的新的应用程序取消它的模型将需要一个外键relationg的联系电话。这现在意味着它现在被绑定到“联系人”,我不能用它说我的电子邮件应用程序。 Django如何从可重用的角度处理这个问题?

回答

1

您可以使用Generic Relations和创建从退订模式向接触模型Generic Foreign Key关系。这允许您抽象取消订阅和其他对象之间的关系,将它们连接到项目中模型的任何实例。

一个正常的ForeignKey只能“指向”另一个模型,这意味着如果TaggedItem模型使用ForeignKey,它将不得不选择一个模型来存储标签。该CONTENTTYPES应用程序提供了一个特殊的字段类型(GenericForeignKey),它解决了这个问题,并允许的关系,是与任何型号的

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

class Unsubscription(models.Model): 
    name = ... 

    # These two fields allow you to manage the model & instance of object that 
    # this unsubscribe model instance is related to 
    content_type = models.ForeignKey(ContentType) 
    object_id = models.PositiveIntegerField() 
    # This gives you an easy way to get access to the actual instance of the 
    # instance above 
    content_object = generic.GenericForeignKey('content_type', 'object_id') 


# On the reverse end of the relationship you can add a Generic relation to 
# easily get access to all unsubscriptions related to this contact via the GFK 
from myapp.models import Unsubscription 
class Contact(models.Model): 
    name = ... 

    unsubscribtions = generic.GenericRelation(Unsubscribtion) 
1

通常它是确定以应用程序之间导入模型。这只会创建一个依赖关系,这是许多应用程序所具有当然,让您的应用独立可插入会更加灵活,但重要的是您可以为任何试图使用您的应用的人记录任何依赖关系。

如果您确实希望您的应用可以插入,请考虑重新组织您的应用。简单是件好事,但过分强调并坚持严格的原则坚持原则会阻碍功能。 (没有你的应用程序的具体细节,这只是推测,但因为你描述的所有应用程序都围绕联系人,它似乎可以简单地重新打包到同一个应用程序中,并退订为联系人和视图中的布尔字段设置属性,并取决于你想要用电子邮件做什么,类似的东西)

相关问题