<p>看看django内置的<a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#ref-contrib-contenttypes" rel="noreferrer">contenttypes framework</a>:</p>
<p><code>django.contrib.contenttypes</code></p>
<p>它允许您将应用程序开发为独立的单元。这就是django开发人员用来允许django的内置<a href="http://docs.djangoproject.com/en/dev/ref/contrib/comments/#ref-contrib-comments-index" rel="noreferrer">comment framework</a>将注释附加到项目中的任何模型的方法。</p>
<p>例如,如果有一些内容对象要“附加”到不同类型的其他内容对象,例如允许每个用户在博客文章、图像或用户配置文件上留下一个“最喜爱的”星,则可以创建一个<code>Favorite</code>模型,该模型使用<a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#generic-relations" rel="noreferrer">generic relation field</a>,如下所示:</p>
<pre><code>from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
class Favorite(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
</code></pre>
<p>通过这种方式,您可以将来自任何用户的<code>Favorite</code>星添加到项目中的任何模型。如果要通过收件人模型类添加API访问,可以在收件人模型上添加一个<a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations" rel="noreferrer">reverse generic relation field</a>(尽管这将“耦合”这两个模型,您说过要避免这样做),或者使用收件人实例的<code>content_type</code>和<code>object_id</code>通过<code>Favorite</code>模型进行查找,请参见<a href="http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#reverse-generic-relations" rel="noreferrer">official docs</a>示例。</p>