Search code examples
djangomanytomanyfield

possible to add to Django ManyToManyField with only instance IDs


Is it possible to add to a ManyToManyField when you've only the list of IDs, without a db hit to retrieve instances (add_instances_but_with_db_hit does this, but with a hit).

Thanks.

class WorkerCombinedPayment(AbstractReimbursement):
    charge_id = models.TextField(blank=True, null=True)
    paid = models.BooleanField(default=False)
    worker = models.ForeignKey(Worker)

class MassPayment(TimeStampedModel):
    list_payments = JSONField(blank=True, null=True)
    paypal_batch_id = models.TextField(blank=True, null=True)
    success = models.NullBooleanField()
    response_from_paypal = JSONField(blank=True, null=True)
    workercombinedpayments = models.ManyToManyField(WorkerCombinedPayment)

    def add_instances_but_with_db_hit(self, id_list):
        found = WorkerCombinedPayment.objects.filter(id__in=id_list)
        self.workercombinedpayments.add(found)

Solution

  • Yes, you can just pass the IDs:

    self.workercombinedpayments.add(*id_list)