H C
H C

Reputation: 1200

How to access foreign fields through a queryset through two filters?

I have the following models:

class pair(models.Model):
    user = models.ForeignKey(User)
    institution = models.ForeignKey(Institution)

class Institution(models.Model):
    name = models.CharField(max_length=250)

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(verbose_name='email address', max_length=255, unique=True)

I would like to filter by user and grab the name of their associated institution. The below filter doesn't seem to work:

list_of_accounts = pair.objects.filter(user = request.user.id).values(institution__name)

When I do this, I get "global name 'institution__name' not defined".

Upvotes: 1

Views: 90

Answers (1)

Geo Jacob
Geo Jacob

Reputation: 6009

list_of_accounts = pair.objects.filter(user = request.user.id).values_list('institution__name', flat=True)

'institution__name' should be in single quotes.

or you can fetch like;

list_of_accounts = request.user.pair_set.all().values_list('institution__name', flat=True)

Upvotes: 1

Related Questions