Reputation: 334
I have the following models:
class RecipientList(models.Model):
name = models.CharField(max_length=255)
list_type = models.CharField(max_length=255)
status = models.CharField(max_length=255)
class RecipientListEmail(models.Model):
email = models.CharField(max_length=255)
recipient_list = models.ForeignKey(RecipientList, on_delete=models.DO_NOTHING)
What I'm trying to do is retrieve all RecipientLists and for each recipient list I'd like to get a set of RecipientListEmails associated with it. In other words, it is a simple one-to-many (1 RecipientList to many RecipientListEmails) relationship and I'd like to grab all this information in one result set.
Is it possible to do in Django without iterating over the RecipientList and querying RecipientListEmails individually or writing my own SQL join?
Upvotes: 1
Views: 880
Reputation: 362746
This is one query, is it the mapping you wanted?
output = collections.defaultdict(list)
values = RecipientListEmail.objects.values_list('recipient_list__pk', 'email')
for recipient_id, email in values:
output[recipient_id].append(email)
Upvotes: 2