我真的很难掌握 Django 内容类型的概念。感觉非常骇人听闻,最终与 Python 的做事方式背道而驰。话虽如此,如果我要使用 Django,那么我必须在框架的范围内工作。
所以我来到这里想知道是否有人可以提供一个实际的现实世界示例,说明内容类型如何工作以及您将如何实现它。我看过的几乎所有教程(主要在博客上)都没有很好地真正涵盖这个概念。他们似乎从 Django 文档中断的地方接了过来(似乎无处可去)。
最佳答案
首先问自己这个问题:“这些模型中的任何一个都需要以相同的方式与其他模型相关联吗?或者我以后会以不可预见的方式重用这些关系吗?”我们问这个问题的原因是因为这是 Content Types 框架最擅长的:它创建了模型之间的通用关系。等等,让我们深入研究一些代码,看看我的意思。
# ourapp.models
from django.conf import settings
from django.db import models
# Assign the User model in case it has been "swapped"
User = settings.AUTH_USER_MODEL
# Create your models here
class 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.models
from django.contrib.contenttypes.fields import GenericForeignKey
from 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
, 也是一个 ForeignKey
至ContentType
和 PositiveIntegerField
对于object_id
.这些字段用于告诉 Django 这与什么类型的对象相关以及该对象的 id 是什么。实际上,这是有道理的,因为 Django 需要同时查找这些相关对象。
您可能正在寻找可以使Guido van Rossum 的密封、一尘不染、直观的代码。自豪的。我明白了。我们来看看GenericRelation
场,这样我们就可以在这上面打个漂亮的弓。
# ourapp.models
from 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')
砰!就像这样,您可以使用这两个模型的评论。事实上,让我们继续在我们的 shell 中执行此操作(从您的 Django 项目目录中输入 python manage.py shell
)。
>>> from django.contrib.auth import get_user_model
>>> from ourapp.models import Picture, Post
# We use get_user_model() since we are referencing directly
User = 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.models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from chatterly.models import Comment
# For a third time, we take the time to ensure custom Auth isn't overlooked
User = settings.AUTH_USER_MODEL
# Create your models here
class 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)
我希望你们觉得这很有帮助,因为我很想遇到一些向我展示 GenericForeignKey
更现实应用的东西和 GenericRelation
字段。
就像生活中的任何事情一样,有利也有弊。每当您添加更多代码和更多抽象时,底层流程就会变得更重且更慢。添加通用关系可以增加一点性能阻尼器,尽管它会尝试智能缓存其结果。总而言之,它归结为清洁和简单是否超过了小的性能成本。对我来说,答案是一百万次是的。
内容类型框架的内容比我在这里展示的要多。有一个完整的粒度级别和更详细的用法,但对于普通人来说,我认为这就是你将使用它的 10 次中的 9 次。
一个相当大的警告是,当您使用 GenericRelation
, 如果模型具有 GenericRelation
已应用 ( Picture
) 被删除,所有相关 ( Comment
) 对象也将被删除。或者至少在撰写本文时。
https://stackoverflow.com/questions/20895429/