John Crichton
John Crichton

Reputation: 77

Get queryset of foreignkey

I need to obtain a queryset of a foreignkey but I haven't been able to figured out how.

I have the following model:

class Contact(models.Model):
    owner = models.ForeignKey(CustomUser, related_name='contact_set')
    referenced = models.ForeignKey(CustomUser, related_name='contacted_by_set')

Then, for the current user I need a queryset that retrieves the referenced Users. The following returns Contact objects, I need User objects:

print request.user.contact_set.all()

Also, it needs to be a queryset because it will be used by a ModelMultipleChoiceField.

Thanks

Upvotes: 0

Views: 1814

Answers (2)

ojii
ojii

Reputation: 4781

User.objects.filter(contacted_by_set__owner=request.user) 

should do it

Upvotes: 2

Daniel Roseman
Daniel Roseman

Reputation: 599490

Oji is correct with the syntax, but I would point out that this is actually a ManyToMany relationship. If you've shown the complete Contact definition, and there aren't any other tables, you could miss out the entire table and just define the relationship directly on CustomUser:

contacts = ManyToManyField('self', related_name='referenced_users')

Or, if you do have other fields on Contact, you can add through='Contact' on that ManyToManyField.

In either case, the query then becomes:

request.user.referenced_users.all()

Upvotes: 1

Related Questions