Asma Gheisari
Asma Gheisari

Reputation: 6254

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:

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

Upvotes: 0

Views: 74

Answers (2)

César
César

Reputation: 10119

how can i get an instance instead of a query set when using this 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? 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'. 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 ;)

Upvotes: 1

dm03514
dm03514

Reputation: 55952

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.

Upvotes: 1

Related Questions