关于Django orm models文件定义函数的写法
Posted tangda
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Django orm models文件定义函数的写法相关的知识,希望对你有一定的参考价值。
models.py
class Candidate(BaseModel):
name = models.CharField(max_length=64,
verbose_name="候选人姓名",
null=True,
blank=True)
email = models.EmailField(null=True,
blank=True,
verbose_name="候选人邮箱")
code = models.CharField(max_length=48,
verbose_name="每张表数据对应的uuid",
null=True,
blank=True)
expire_time = models.DateTimeField(null=True,
verbose_name=‘过期时间‘)
class Meta:
verbose_name = "候选人表"
verbose_name_plural = verbose_name
def __str__(self):
return self.name
class InvitationJobInterviewForm(BaseModel): invite_people = models.ForeignKey(to=‘Employees‘, verbose_name=‘邀请人‘, null=True, blank=True, related_name=‘invite_people_in_employees‘, on_delete=models.CASCADE) invited_people = models.ForeignKey(to=‘Candidate‘, verbose_name=‘被邀请人‘, null=True, blank=True, related_name=‘invited_people_in_candidate‘, on_delete=models.CASCADE) invite_people_code = models.CharField(max_length=64, verbose_name="邀请人code", null=True, blank=True) jobs = models.ForeignKey(to=‘Jobs‘, verbose_name="招聘职位", null=True, blank=True, on_delete=models.CASCADE, related_name=‘invite_people_jobs‘) class Meta: verbose_name = ‘邀请职位面试表‘ verbose_name_plural = verbose_name @property def get_invite_people_name(self): try: self.invite_people.name except Exception: return ‘null‘ return self.invite_people.name @property def get_invited_people_name(self): try: self.invited_people.name except Exception: return ‘null‘ return self.invited_people.name @property def get_job_name(self): try: self.jobs.jobname except Exception: return ‘null‘ return self.jobs.jobname def __str__(self): return self.invite_people_code
以候选人表举例,
def get_invited_people_name(self): try: self.invited_people.name except Exception: return ‘null‘ return self.invited_people.name
self.invited_people 跨到外键关联的表中 self.invited_people.name跨到另外一张表中获取到name (这是正向查询)
如果外键在另一张表中,也可以直接点另外一张表中的外键,这样可以在本张表跨到关联的那张表,再点name 即可获得到另一张表里面的name(反向查询)
以上是关于关于Django orm models文件定义函数的写法的主要内容,如果未能解决你的问题,请参考以下文章
Django models ORM基础操作--白话聊Django系列