Search code examples
djangofilteruniquedjango-querysetone-to-many

django objects.filter(x__in = y) where y is repetitive QuerySet


Customer.objects.filter(customer_id__in=contact_list_senders)

contact_list_senders is a repetitive QuerySet that involves some customer_ids:

{sender_id1, sender_id2, sender_id1, sender_id2, sender_id1}

When I try to find the Customer objects from the contact_list_senders QuerySet with the above code

Actual Output:

{Customer1, Customer2}

Desired Output

{Customer1, Customer2, Customer1, Customer2, Customer1}

I understand the actual output makes sense because there are only 2 Customer objects that matches with these contacts. Can you please help me to get the desired outcome?

models.py:

class Customer(models.Model):
    customer_id = models.CharField(max_length=244, blank=False, null=False)
    first_name = models.CharField(max_length=244, blank=True, null=True)
    last_name = models.CharField(max_length=244, blank=True, null=True)
    email = models.CharField(max_length=244, blank=False, null=False)
    enrollment_method = models.CharField(max_length=244, blank=True, null=False)
    account_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2)
    reserved_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2)
    modified = models.DateTimeField(auto_now_add=True)
    created = models.DateTimeField(auto_now_add=True)

Solution

  • You have a good start, but you'll have to do the rest in python:

    customers = {x.customer_id: x for x in Customer.objects.filter(customer_id__in=contact_list_senders)}
    final_customer_list = [customers[x] for x in contact_list_senders]
    

    This first builds a dictionary mapping customer IDs to customers (without a database query for every one), and then uses that to build the final list, including duplicates.

    It is assuming that your first list is a list of customer IDs, but can easily be adapted if not.