链接到几个指定模型之一的django foreignkey
django-multiforeignke的Python项目详细描述
django多重点火键
Django ForeignKey,链接到几个指定型号中的一个:
classComment(models.Model):user=models.ForeignKey(User)text=models.TextField()# users may leave comments for blog posts, articles or votingsobject=MultiForeignKey(Post,Article,Voting)
与^ {TT1}$不同,该字段使用本机数据库外键,并提供最大速度和可靠性。
警告
这是一个初步的alpha版本,很可能没有完全按照广告的那样工作。我不得不在未完成的情况下发布它,因为我必须在我的项目中使用它。
安装
pip install django-multiforeignkey
用法
将multiforeignkey添加到INSTALLED_APPS:
# settings.pyINSTALLED_APPS=[...'multiforeignkey',]
在模型中添加一个字段:
# comments/models.pyfrommultiforeignkey.modelsimportMultiForeignKeyclassComment(models.Model):user=models.ForeignKey(User)text=models.TextField()# users may leave comments for blog posts, articles or votingsobject=MultiForeignKey(Post,Article,Voting)
创建相应的数据库表:
./manage.py makemigrations && ./manage.py migrate
将新字段用作真正的数据库字段:
comment=Comment.objects.filter(object=post)assertcomment.objectispostcomment.object=votingassertcomment.objectisvotingcomment.save()
或使用特定子字段:
comment=Comment.objects.filter(post=post)assertcomment.postispostassertcomment.articleisNoneassertcomment.votingisNonecomment.voting=votingassertcomment.postisNoneassertcomment.articleisNoneassertcomment.votingisvotingcomment.save()