[英]Assigning Django model field within one model to point to one of a choice of other, related models
I am designing an inspection app in Django for a service company and have an esoteric question about my models. 我正在用Django为服务公司设计一个检查应用程序,并对我的模型有一个深奥的问题。 This is the scenario I'm struggling with:
这是我正在努力解决的情况:
Site(models.Model):
name = CharField()
Generator(models.Model):
number = CharField()
site = ForeignKey(Site)
Pump(models.Model):
number = CharField()
site = ForeignKey(Site)
Jobs(models.Model):
asset = ?
site = ForeignKey(Site)
What I would like to do is assign either a Generator OR a Pump object to the asset field in Jobs. 我想做的是将一个Generator或Pump对象分配给Jobs中的资产字段。 Rather than just generating a list of both generator and pump numbers I would like the field to point to the actual model itself, that way I can backwards reference each job without scanning both tables.
我不仅希望生成发电机和泵编号的列表,还希望该字段指向实际模型本身,这样我就可以向后引用每个作业,而无需扫描两个表。
Any ideas? 有任何想法吗? Would it help to have an asset property in the job model?
在工作模型中拥有资产属性是否有帮助? I am overthinking this?
我在想这个吗?
Using Django 1.11.1 and Python 3.6 使用Django 1.11.1和Python 3.6
You can use a generic foreign key as seen in the documentation 您可以使用文档中所示的通用外键
Since this is a one-line answer. 由于这是单行答案。 To expand upon that:
对此进行扩展:
from django.db import models
from django.contrib.contenttypes.fields import GenericRelation
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Asset(models.Model):
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
...
class Job(models.Model):
assets = GenericRelation(Asset)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.