【发布时间】:2012-10-24 22:39:51
【问题描述】:
我正在构建一个类似于通讯录的应用。对于我的一个观点,我有一个个人列表。每个Individual 都有一个Role,它将他们与他们的职位和雇主联系起来。有几种不同类型的雇主,所以这是一个通用关系。
使用 ListView 通用视图,我创建了一个个人列表,其中显示了他们的姓名、职务和雇主,即
“吉米,大通银行官员”
“总医院首席执行官玛丽”
我需要将公司名称作为链接到公司详细信息页面。
问题
由于我有一个用于此列表的模板,我很难理解如何根据个人拥有的雇主类型(即银行或医院)更改网址。
什么可能有效
我是否应该为视图编写一个函数来获取雇主内容类型并创建一个变量?或者我应该把函数放在
Role模型下?我是 python/Django 的菜鸟,甚至不知道如何写这个。我尝试在模板中使用 if/else 语句,即如果银行,使用此 url,但它不起作用。可能是因为它是一个通用关系,我的查询不正确。
回应以下评论:
我不确定您所说的继承结构到底是什么意思,但这里是我的模型的简化版本;
class Individual(models.Model)
name = models.CharField(max_length=30)
class Bank(models.Model):
name = models.CharField(max_length=30)
staff = generic.GenericRelation('Role',
content_type_field='employer_content_type',
object_id_field='employer_id'
)
class Hospital(models.Model):
name = models.CharField(max_length=30)
staff = generic.GenericRelation('Role',
content_type_field='employer_content_type',
object_id_field='employer_id'
)
... and so on for each different employer
class Role(models.Model):
title = models.CharField(max_length=70)
job_holder = models.ForeignKey(Individual)
employer_content_type = models.ForeignKey(ContentType,
limit_choices_to={"model__in": ('venue', 'festival', 'artsorganization','bookingagent', 'managementcompany', 'mediaoutlet', 'otherorganization', 'presentercompany', 'publishingcompany', 'presenter', 'recordcompany', 'musician', 'ensemble')}, related_name="employer")
employer_id = models.PositiveIntegerField()
employer = generic.GenericForeignKey('employer_content_type', 'employer_id')
曾几何时,我让所有雇主都继承了公司模式。我改变了它,因为每个雇主都有不同的属性,这让事情变得非常复杂。
谢谢!
【问题讨论】:
-
您能否补充一下您是如何定义您的 Employers 的继承结构的?
-
嗨@dokkaebi 我添加了我的模型结构以回应您的评论。它给了我一个想法!如果我制作了一个公司模型,每个不同类型的公司都有 OneToOne 关系怎么办?那么 url 可能是相同的,详细页面将仅根据 if 语句显示不同的信息...