多个模型或查询集的外键
Is it possible to make a ForeignKey to more than one model? I want to choose from different models like Parts and Machines Model.
I read this to combine multiple models into one list: How to combine multiple querysets in Django?
How can I get the foreign key to that list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我知道您一年多前就问过这个问题,但我也遇到了类似的问题,我想为未来的读者分享解决方案的链接。
一般来说,contenttypes框架解决了这个问题,并且我想这就是丹尼尔·罗斯曼所说的。
如何在 Django 中使用动态外键?
I know that you asked this over a year ago, but I had a similar problem and I want to share a link to the solution for future readers.
Generally the contenttypes framework solves this problem, and I guess this is what Daniel Roseman was talking about.
How to use dynamic foreignkey in Django?
您需要通用关系。
通用关系允许您动态定位外键的模型。
You need generic relations.
A generic relation allows you to dynamically target the
Model
of the foreign key.我将为这个问题提供一个全面的答案,我知道它已经很老了,但它仍然相关。
我们将使用 通用关系。
首先,在
settings.py
中,确保django.contrib.contenttypes
包含在INSTALLED_APPS
数组中。让我们在
models.py
中创建一个新模型:通过
content_type
,我们可以将Image
与任何其他模型类关联,而object_id 将保存另一个模型实例。
要从
Company
实例引用Image
模型,我们需要创建一个 反向泛型关系在
schema.py
中,我们可以创建Image
在Company
实例中,例如:company_instance.images
字段只是一个GenericRelatedObjectManager
(docs)这是最终的Image 表在数据库中的外观:
I'll provide a comprehensive answer for this question, I know its quite old, but it's still relevant.
We're gonna be using Generic Relations.
First, in
settings.py
make sure thatdjango.contrib.contenttypes
is included in theINSTALLED_APPS
array.Let's create a new model in
models.py
:With
content_type
we can associateImage
with any other model class, whileobject_id
will hold the other model instance.To refer back to the
Image
model from aCompany
instance we need to make a reverse generic relationIn
schema.py
, we can createImage
s in aCompany
instance like:the
company_instance.images
field is just aGenericRelatedObjectManager
(docs)This is how the final
Image
table looks in the database:Django 多态库 提供了一个简单的解决方案,应该可以很好地工作管理和表单也使用表单集。
例如:
这样,您可以使用父模型将所有者设置为
Staff
或Student
实例,或者直接使用子模型。The Django-polymorphic library provides a simple solution that should work well with the admin and forms too using formsets.
For example:
With this, you can use the parent model to set the owner to either a
Staff
orStudent
instance or use the child models directly.