79236336

Date: 2024-11-29 08:37:08
Score: 0.5
Natty:
Report link

I've solved this problem by combining the address from & address to primary keys into annotated unique key - uk - field and filter each uk.

from django.db.models import CharField, Value
from django.db.models.functions import Concat

orders = models.Order.objects.annotate(
    addresses_uk=Concat('address_from__pk', Value('-'), 'address_to__pk',
    output_field=CharField())
    )

for uk in set(orders.values_list('addresses_uk', flat=True)):
    bill = models.Bill.objects.create(
        address_from=models.Address.objects.get(pk=int(uk.split("-")[0])),
        address_to=models.Address.objects.get(pk=int(uk.split("-")[1]))
    )
    orders.filter(addresses_uk=uk).update(bill=bill)
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Ahmed Ashraf