Home > Back-end >  Django - Get a single queryset values list from two related models
Django - Get a single queryset values list from two related models

Time:12-12

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='[email protected]').prefetch_related('secondary_emails').values_list('email')
>>> <QuerySet [('[email protected]',)]>

The related SecondaryEmails model contains another two emails '[email protected]', '[email protected]'. I wanted these two emails also to be appended in the values_list() like the following:

<QuerySet [('[email protected]',), ('[email protected]',), ('[email protected]',)]>

Thanking you in advance.

CodePudding user response:

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='[email protected]').prefetch_related('secondary_emails').values_list('email', 'secondary_emails__email')
  • Related