Django - Get a single queryset values list from two related models

I have an user model

class User(AbstractBaseUser):
    name = models.CharField(max_length=100, default='Default')
    email = models.EmailField(
        verbose_name='email address',
        max_length=255,
        unique=True,
    )
    active = models.BooleanField(default=True)

and a related SecondaryEmails model

class SecondaryEmails(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='secondary_emails')
    email = models.EmailField()
    is_validated = models.BooleanField(default=False)

Now I want to create a method to get a values_list containing both the User model's email and all the emails stored in the related SecondaryEmails model.

I am able to get a values_list containing only the email of the User model

>>> User.objects.filter(email='test@gmail.com').prefetch_related('secondary_emails').values_list('email')
>>> <QuerySet [('test@gmail.com',)]>

The related SecondaryEmails model contains another two emails 'a1@gmail.com', 'a2@gmail.com'. I wanted these two emails also to be appended in the values_list() like the following:

<QuerySet [('test@gmail.com',), ('a1@gmail.com',), ('a2@gmail.com',)]>

Thanking you in advance.

the related email should have the field name 'secondary_emails__email' so you need to include that in the values_list():

User.objects.filter(email='test@gmail.com').prefetch_related('secondary_emails').values_list('email', 'secondary_emails__email')
Back to Top