因此,你想在工作中使用Content Types框架吗?
首先问自己一个问题:“这些模型中的任何一个是否需要以相同的方式与其他模型相关联,和/或以后是否会以无法预见的方式重用这些关系?” 我们问这个问题的原因是因为这是Content Types框架最擅长的:它在模型之间创建通用关系。等等,让我们深入研究一些代码,看看我的意思。
# ourapp.modelsfrom django.conf import settingsfrom django.db import models# Assign the User model in case it has been "swapped"User = settings.AUTH_USER_MODEL# Create your models hereclass Post(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=75) slug = models.SlugField(unique=True) body = models.TextField(blank=True)class Picture(models.Model): author = models.ForeignKey(User) image = models.ImageField() caption = models.TextField(blank=True)class Comment(models.Model): author = models.ForeignKey(User) body = models.TextField(blank=True) post = models.ForeignKey(Post) picture = models.ForeignKey(Picture)
好的,因此我们确实有一种理论上可以建立这种关系的方法。但是,作为Python程序员,你的卓越才智告诉你这很糟糕,你可以做得更好。击掌!
进入内容类型框架!
好了,现在我们将仔细研究我们的模型,并对其进行重新设计以使其更加“可重用”和直观。让我们从摆脱Comment模型上的两个外键开始,并用替换它们GenericForeignKey。
# ourapp.modelsfrom django.contrib.contenttypes.fields import GenericForeignKeyfrom django.contrib.contenttypes.models import ContentType...class Comment(models.Model): author = models.ForeignKey(User) body = models.TextField(blank=True) content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = GenericForeignKey()
所以发生了什么事?好吧,我们进入并添加了必要的代码以允许与其他模型的通用关系。请注意,除了之外GenericForeignKey,还有一个 ForeignKeyto ContentType和a PositiveIntegerField的问题object_id。这些字段用于告诉Django与之相关的对象类型以及该对象的ID。实际上,这是有道理的,因为Django将需要同时查找这些相关对象。
好吧,这不是非常像Python的…有点丑陋!
你可能正在寻找能使Guido van Rossum感到骄傲的气密,一尘不染,直观的代码。我明白了 让我们看看这个GenericRelation领域,以便我们对此锦上添花。
# ourapp.modelsfrom django.contrib.contenttypes.fields import GenericRelation...class Post(models.Model): author = models.ForeignKey(User) title = models.CharField(max_length=75) slug = models.SlugField(unique=True) body = models.TextField(blank=True) comments = GenericRelation('Comment')class Picture(models.Model): author = models.ForeignKey(User) image = models.ImageField() caption = models.TextField(blank=True) comments = GenericRelation('Comment')am!就像这样,你可以为这两个模型使用“注释”。实际上,让我们继续在shell中进行操作(python manage.py shell从Django项目目录中键入)。
>>> from django.contrib.auth import get_user_model>>> from ourapp.models import Picture, Post# We use get_user_model() since we are referencing directlyUser = get_user_model()# Grab our own User object>>> me = User.objects.get(username='myusername')# Grab the first of our own pictures so we can comment on it>>> pic = Picture.objects.get(author=me)# Let's start making a comment for our own picture>>> pic.comments.create(author=me, body="Man, I'm cool!")# Let's go ahead and retrieve the comments for this picture now>>> pic.comments.all()[<Comment: "Man, I'm cool!">]# Same for Post comments>>> post = Post.objects.get(author=me)>>> post.comments.create(author=me, body="So easy to comment now!")>>> post.comments.all()[<Comment: "So easy to comment now!"]
就这么简单。
这些“一般”关系的其他实际含义是什么?
通用外键可以减少各种应用程序之间的干扰。例如,假设我们将Comment模型拉到了自己的名为的应用中chatterly。现在,我们要创建另一个名为“ noise_nimbus人们存储音乐以与他人共享”的应用程序。
如果我们想在这些歌曲中添加评论怎么办?好吧,我们可以得出一个通用关系:
# noise_nimbus.modelsfrom django.conf import settingsfrom django.contrib.contenttypes.fields import GenericRelationfrom django.db import modelsfrom chatterly.models import Comment# For a third time, we take the time to ensure custom Auth isn't overlookedUser = settings.AUTH_USER_MODEL# Create your models hereclass Song(models.Model): ''' A song which can be commented on. ''' file = models.FileField() author = models.ForeignKey(User) title = models.CharField(max_length=75) slug = models.SlugField(unique=True) description = models.TextField(blank=True) comments = GenericRelation(Comment)
我希望你们发现这对你有所帮助,因为我很想遇到一些向我展示了GenericForeignKeyand GenericRelation领域更实际应用的东西。
这好得令人难以置信吗?
就像生活中的任何事情一样,也各有利弊。每当你添加更多代码和更多抽象时,基础流程就会变得更重且更慢。尽管添加通用关系可能会尝试并智能缓存其结果,但可能会增加一点性能衰减器。总而言之,这取决于清洁度和简单性是否超过了较小的性能成本。对我来说,答案是一百万次。
内容类型框架比我在这里显示的要多。有一个整体的粒度级别和更详细的用法,但是对于一般个人而言,我认为这就是你将十分之九地使用它的方式。
通用关联器(?)当心!
一个相当大的警告是,当你使用时
GenericRelation,如果删除了已
GenericRelation应用(
Picture)的模型,则所有相关(
Comment)对象也将被删除。或至少在撰写本文时。



