如何在Django中使用动态外键? [英] How to use dynamic foreignkey in Django?
本文介绍了如何在Django中使用动态外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想连接一个 ForeignKey
到两个不同的模型。
I want to connect a single ForeignKey
to two different models.
例如:
我有两个名为 Casts
和文章
的模型,第三个模型, 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')
到Faves
和
to Faves and
fields.GenericRelation(Faves)
到文章和演员
这篇关于如何在Django中使用动态外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文