简体   繁体   English

在ManyToMany关系中访问对象时出错

[英]error while accessing objects in ManyToMany relationship

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: 每件事情都很好,直到这里。现在我想从这个机构获得这个机构我已经agnposition很多这样的事情:

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 在此先感谢任何帮助:D

first off i think convention is to use lowercase with underscores for attributes in python classes, 首先,我认为约定是使用带有下划线的小写字母表示python类中的属性,

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. 接下来,当您使用user.agencyposition_set.all()[:1]我认为返回一个查询集对象而不是您想要的类的实例,我认为您可能只需要一个实例来访问其属性。

To get a users Agency you can user.agencypostiion_set.all()[0].Agency This should be an agency object connected to the particular user. 要获得用户代理,您可以使用user.agencypostiion_set.all()[0].Agency这应该是连接到特定用户的代理对象。

how can i get an instance instead of a query set when using this user.agencyposition_set.all()[:1] ? 使用此user.agencyposition_set.all()[:1]时,如何获取实例而不是查询集?

If you slice a queryset you get another queryset, so if you need an instance just do: 如果您对查询集进行切片,则会获得另一个查询集,因此如果您需要实例,请执行以下操作:

agnposition = user.agencyposition_set.all()[0]

Is there a typo in your AgencyPosition class? 您的AgencyPosition类中是否存在拼写错误? Is it?: 是吗?:

class AgencyPosition(models.Model):
    Agency=models.ForeignKey(Agent)
    ...

Or: 要么:

class AgencyPosition(models.Model):
    Agency=models.ForeignKey(Agency)
    ...

Update 更新

I don't think is correct to do: 我不认为这样做是正确的:

agn=Agency.objects.get(pk=agnposition.agency_set.id)

'agency_set' is a RelatedManager object and has no attribute 'id'. 'agency_set'是一个RelatedManager对象,没有属性'id'。 Try this: 尝试这个:

agnposition = user.agencyposition_set.all()[0]
agn = Agency.objects.get(pk=agnposition.agency.pk)

And please oh god please don't you uppercase for your field names ;) 请上帝,请不要为你的字段名称大写;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM