如何根据父模型中的字段过滤对象

问题描述 投票:0回答:1

我想找到曾经拜访过患者的治疗师。 我的访问模型:

class visit(models.Model):
    costumer_name=models.ForeignKey(costumerprofile, on_delete=models.CASCADE)
    therapist_name=models.ForeignKey(therapistProfiles, on_delete=models.CASCADE, default=1) 

第一个查询工作正常,但找不到第二个查询的匹配查询:

@property
def getthefee(self):
        costumer = costumerprofile.objects.get(c_name=self.costumer_name)
        therapist=therapistProfiles.objects.get(name=self.therapist_name)
       
 

所以我使用了这个过滤:

 therapist=therapistProfiles.objects.distinct().filter(name__contains=str(self.therapist_name)[0:10])

它工作得很好,但是当我将字符串长度更改为 11 或更长时,它返回 None。

治疗师模型与用户模型具有一对一的关系,但客户模型则不然。

class costumerprofile(models.Model):
   c_name= models.CharField(max_length=40,  null=True, blank=True)

class therapistProfiles(models.Model):
   user=models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
   name=models.CharField(max_length=30, null=True, blank=True)
django filtering
1个回答
0
投票

在访问模型中,customer_name 和 therapy_name 是 customerprofile 和 therapyprofile 的实例。 您可以按如下方式替换它们:

class visit(models.Model):
    costumer = models.ForeignKey(costumerprofile, on_delete=models.CASCADE)
    therapist = models.ForeignKey(therapistProfiles, on_delete=models.CASCADE, default=1)

可以直接访问相关字段及其属性,无需使用 get() 获取对象

© www.soinside.com 2019 - 2024. All rights reserved.