预期结果:我想查询与协调程序相关的父对象。请帮助我如何实现这样的目标。
在运行以下查询集后出现错误,
user.coordinator.agent.parent_set.all()模型
class Coordinator(models.Model):
user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)
region = models.CharField(max_length=15, null=True, blank=True, choices=REGION)
id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True)
address = models.TextField(null=False, blank=False)
gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER)
created_at = models.DateTimeField(auto_now_add=True)
class Agent(models.Model):
user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)
coordinator = models.ForeignKey(Coordinator, null=True, blank=True, on_delete=SET_NULL)
region = models.CharField(max_length=15, null=True, blank=True, choices=REGION)
id_no = id_no = models.CharField(max_length=150, null=False, blank=False, unique=True,)
address = models.TextField(null=False, blank=False)
gender = models.CharField(max_length=20, null=False, blank=False, choices=GENDER)
created_at = models.DateTimeField(auto_now_add=True)
class Parent(models.Model):
agent = models.ForeignKey(Agent, null=True, blank=True, on_delete=SET_NULL)
surname = models.CharField(max_length=150, null=False, blank=False)
first_name = models.CharField(max_length=150, null=False, blank=False)
other_name = models.CharField(max_length=150, null=True, blank=True)
address = models.CharField(max_length=200, null=True, blank=True)
region = models.CharField(max_length=15, null=True, blank=True, choices=REGION)
dob = models.CharField(max_length=10, null=False, blank=False)发布于 2022-01-17 16:28:44
您不能使用user.coordinator.agent.parent_set.all(),因为coordinator和agent之间没有直接关系。你应该这样做:
# Starting from a Coordinator
coordinator.user.agent.parent_set.all()
# Starting from a user
user.agent.parent_set.all()注意,这可能会引发异常,因为您的OneToOneFields是可空的。
您必须更改您的模型以使您的查询工作如下:
class Agent(models.Model):
coordinator = OneToOneField(Coordinator, null=True, blank=True, on_delete=models.SET_NULL)
# Instead of
user = OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)https://stackoverflow.com/questions/70743134
复制相似问题