访问多对多关系中的对象时出错
我有这两种模型:
class Agency(models.Model):
Location=models.ForeignKey(Location)
Name=models.CharField(max_length=50)
WebSite=models.CharField(max_length=100)
class AgencyPosition(models.Model):
Agency=models.ForeignKey(Agency)
Users=models.ManyToManyField(User)
PhoneNumber=models.CharField(max_length=50)
Email=models.CharField(max_length=50)
当用户登录时,我想获得用户所属的机构。 我用它来获取用户的位置:
agnposition=user.agencyposition_set.all()[:1]
直到这里一切都很好。现在我想从 agnposition
获得代理我已经尝试了很多这样的事情:
agn=Agency.objects.get(pk=agnposition.agency_set.id)
或者
agn=Agency.object.filter(pk=agnposition.Agency.id)
或者
agn=Agency.object.filter(pk=agnposition__Agency.id)
但是他们都有这样的错误:'
'QuerySet' object has no attribute 'Agency'
我该如何处理这个问题?
预先感谢您的帮助:D
I have these 2 models:
class Agency(models.Model):
Location=models.ForeignKey(Location)
Name=models.CharField(max_length=50)
WebSite=models.CharField(max_length=100)
class AgencyPosition(models.Model):
Agency=models.ForeignKey(Agency)
Users=models.ManyToManyField(User)
PhoneNumber=models.CharField(max_length=50)
Email=models.CharField(max_length=50)
when user login I wanna get the agency that user is belonge to.
I use this to get user's position:
agnposition=user.agencyposition_set.all()[:1]
every thing is good til here.now i wanna get the agency from agnposition
I've tryed so many things like this:
agn=Agency.objects.get(pk=agnposition.agency_set.id)
or
agn=Agency.object.filter(pk=agnposition.Agency.id)
or
agn=Agency.object.filter(pk=agnposition__Agency.id)
but all of them had errors like this:'
'QuerySet' object has no attribute 'Agency'
how can I handle this?
thanks in advance for any help :D
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,我认为约定是在 python 类中使用小写字母和下划线作为属性,
接下来,当您使用
user.agencyposition_set.all()[:1]
我认为返回一个查询集对象而不是实例对于您想要的类,我认为您可能只需要一个实例来访问其属性。要获取用户代理,您可以
user.agencypostiion_set.all()[0].Agency
这应该是连接到特定用户的代理对象。first off i think convention is to use lowercase with underscores for attributes in python classes,
Next, when you use
user.agencyposition_set.all()[:1]
i think that returns a queryset object not an instance of the class you want, i think you might need just an instance to access its attributes.To get a users Agency you can
user.agencypostiion_set.all()[0].Agency
This should be an agency object connected to the particular user.如果您对一个查询集进行切片,您会得到另一个查询集,因此如果您需要一个实例,只需执行以下操作:
您的 AgencyPosition 类中是否有拼写错误?是吗?:
或者:
更新
我认为这样做不正确:
“agency_set”是一个RelatedManager 对象,没有属性“id”。试试这个:
天哪,请不要将字段名称大写;)
If you slice a queryset you get another queryset, so if you need an instance just do:
Is there a typo in your AgencyPosition class? Is it?:
Or:
Update
I don't think is correct to do:
'agency_set' is a RelatedManager object and has no attribute 'id'. Try this:
And please oh god please don't you uppercase for your field names ;)