我有两个模型,大概是这样的:
class UserProfile(models.Model):
account = models.ForeignKey(MyUser, related_name='profiles') # MyUser is my custom user model
display_name = models.CharField(max_length=30)
...
def get_all_contracts(self):
#returns all contracts associated with the profile
class Contract(models.Model):
...
employee = models.ForeignKey(UserProfile, related_name='employee_contracts')
employer = models.ForeignKey(UserProfile, related_name='employer_contracts')
...
我想在合同模型中编写一个方法,返回不是访问视图的UserProfile
实例,这样如果是访问仪表板的雇员,这个方法将返回雇主,反之亦然,这样我就可以像这样使用它:
{% for contract in user_profile.get_all_contracts %}
<h2>The other user is {{ contract.other_user.display_name }}</h2>
{% endfor %}
在本例中,other_user
将是方法。你知道吗
有办法吗?我不知道如何从方法中检测哪个配置文件是加载页面的配置文件。你知道吗
感谢您的帮助:)
可以将其作为模板标记。比如:
然后在模板循环中:
如果您100%确信
contract.employee
和contract.employer
关系不会为空,那么可以消除IndexError
异常处理程序。你知道吗或者,如果需要访问
other_user
的其他属性,可以将其作为赋值标记来执行:然后在循环中,您可以访问所需的任何属性。你知道吗
相关问题 更多 >
编程相关推荐