[英]Django templates foreign key traversal
I saw multiple questions on this but non worked for me, so I'll query about my specific issue I have a table with several foreign keys pointing to other tables, looks like: 我看到了多个问题,但对我没有用,因此我将查询有关我的特定问题的信息,我有一个表,其中有几个指向其他表的外键,如下所示:
class EventCodes(models.Model):
code_name = models.CharField(max_length=25)
class Severities(models.Model):
severity_name = models.CharField(max_length=15)
class Systems(models.Model):
system_id = models.CharField(max_length=15)
class Events(models.Model):
system_id_fk = models.ForeignKey(Systems)
severity_fk = models.ForeignKey(Severities)
code_fk = models.ForeignKey(EventCodes)
I also have a template that allows a user to define a search criteria per system_id and/or severity_name and/or code_name -> this will give me the relevant records from the Events table 我还有一个模板,该模板允许用户根据system_id和/或严重性名称和/或代码名称定义搜索条件->这将为我提供“事件”表中的相关记录
The only problem is that now when I present them in the results template I present their IDs and not their values (the Django ORM added the id PK for each of these tables) 唯一的问题是,现在当我在结果模板中显示它们时,我将显示它们的ID而不是它们的值(Django ORM为每个表添加了ID PK)
QUESTION: How do i allow the results html which got the queryset of the Events to access the values on the System, Severities, EventCodes tables so I can present their string value and not their non human readable ID 问题:如何允许获得事件的查询集的结果html访问系统,严重性,事件代码表中的值,以便我可以显示其字符串值而不是其非人类可读的ID
You can span relationships by accessing the property by using .
您可以通过使用访问属性来扩展关系
.
Django covers this in the documentation Django在文档中介绍了这一点
an_event = Events.objects.all()[0]
an_event.system_id_fk.system_id
Your naming convention could be a little confusing because for ForeignKey Fields django automatically creates an _id
field on the model: 您的命名约定可能会有些混乱,因为django对于ForeignKey Fields会自动在模型上创建一个
_id
字段:
system_id_fk = models.ForeignKey(Systems)
The above creates a column named system_id_fk_id
in the events
table in your db. 上面的代码在数据库的
events
表中创建了一个名为system_id_fk_id
的列。 But when you access an_event.system_id_fk
it will use the system_id_fk_id
column to query the related objeCT!!! 但是,当您访问
an_event.system_id_fk
,它将使用system_id_fk_id
列查询相关的对象!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.