我试图获取存储在 CandidateSkill 模型(In [5])中的外键实例,但希望避免使用循环。
我尝试过values()
,它只返回存储在 候选 模型中的实际candidate_id(int)
,而不返回实例。
models.py
class Candidate(models.Model):
candidate_id = models.AutoField(primary_key = True)
name = models.CharField(max_length = 255, null = False)
class CandidateSkill(models.Model):
candidate_id = models.ForeignKey('hr.Candidate', on_delete = models.CASCADE)
skill = models.CharField(max_length = 255)
Django Shell
In [1]: from hr.models import CandidateSkill as cds
In [2]: a = cds.objects.filter(skill__icontains = 'py')
In [3]: a
Out[3]: <QuerySet [<CandidateSkill: CandidateSkill object (1)>, <CandidateSkill: CandidateSkill object (2)>, <CandidateSkill: CandidateSkill object (3)>, <CandidateSkill: CandidateSkill object (4)>, <CandidateSkill: CandidateSkill object (10)>]>
In [4]: a[0]
Out[4]: <CandidateSkill: CandidateSkill object (1)>
In [5]: a[0].candidate_id
Out[5]: <Candidate: Clayton Cote>
所以我有办法只获取外键实例并避免使用循环。
答案 0 :(得分:2)
如果我正确理解了您的问题,您想获取所有CandidateSkill包含字符串“ py”的候选人吗?这应该得到您想要的
Candidate.objects.filter(candidateskill__skill__icontains='py')