首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >AttributeError at /coordinator‘协调人’object没有属性'agent‘

AttributeError at /coordinator‘协调人’object没有属性'agent‘
EN

Stack Overflow用户
提问于 2022-01-17 14:41:23
回答 1查看 169关注 0票数 0

预期结果:我想查询与协调程序相关的父对象。请帮助我如何实现这样的目标。

在运行以下查询集后出现错误,

代码语言:javascript
复制
user.coordinator.agent.parent_set.all()

模型

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2022-01-17 16:28:44

您不能使用user.coordinator.agent.parent_set.all(),因为coordinatoragent之间没有直接关系。你应该这样做:

代码语言:javascript
复制
# Starting from a Coordinator
coordinator.user.agent.parent_set.all()
# Starting from a user
user.agent.parent_set.all()

注意,这可能会引发异常,因为您的OneToOneFields是可空的。

您必须更改您的模型以使您的查询工作如下:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70743134

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档