[Fixed]-Django objects.filter(x__in = y) where y is repetitive QuerySet

1👍

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.

👤Ben

0👍

I don’t see any primary index on your table, I suppose the customer_id field should be one. In that case if you have the two models with a many-to-one relationship (many senders can relate to one customer) the models should look something like that:

class Sender(models.Model):
  customer = models.ForeignKey(Customer)
  # .. and the other fields od a sender

class Customer(models.Model):
  customer_id = models.CharField(max_length=244, blank=False, null=False, primary_key=True)
  # .. and the other fields of a customer

And then a queryset:

# Replace all() with filter(your_params)
sender_list = Sender.objects.select_related('customer').all()

your_desired_output = [sender.customer for sender in sender_list]

The selected_related method tells Django to follow the relationship and get the related customer objects in the same query (to avoid running separate queries for every sender when iterating over the queryset). In most databases it would mean a single select with a left join of customers so it would be pretty effective.

I believe it would be the right way to do it in Django. If there’s a reason you don’t use primary keys and/or you cannot make such a relationship between models then you need to try a solution sent by user6731765 or try a raw query.

Leave a comment