如何在 Django 中使用动态外键?
问题描述
我想将单个 ForeignKey
连接到两个不同的模型.
I want to connect a single ForeignKey
to two different models.
例如:
我有两个名为 Casts
和 Articles
的模型,还有第三个模型 Faves
,用于收藏其他模型中的任何一个.如何使 ForeignKey
动态化?
I have two models named Casts
and Articles
, and a third model, Faves
, for favoriting either of the other models. How can I make the ForeignKey
dynamic?
class Articles(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Casts(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Faves(models.Model):
post = models.ForeignKey(**---CASTS-OR-ARTICLES---**)
user = models.ForeignKey(User,unique=True)
这可能吗?
解决方案
我是这样做的:
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import fields
class Photo(models.Model):
picture = models.ImageField(null=True, upload_to='./images/')
caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = fields.GenericForeignKey('content_type', 'object_id')
class Article(models.Model):
....
images = fields.GenericRelation(Photo)
你会添加类似的东西
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = fields.GenericForeignKey('content_type', 'object_id')
致最爱和
fields.GenericRelation(Faves)
到文章和演员
contenttypes 文档
相关文章