[Python] How to make group by in django ORM

Discussão em 'Python' iniciado por Stack, Novembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    I've an Order model as below:

    class Order(models.Model):
    bill = models.ForeignKey(Bill, on_delete=models.PROTECT, null=True, blank=True)
    address_from = models.ForeignKey(Address, on_delete=models.PROTECT)
    address_to = models.ForeignKey(Address, on_delete=models.PROTECT)


    How can I group a queryset from it and iterate in each group like the following:

    bill = models.Bill.objects.get(pk=1)
    groups = models.Order.objects.all().group_by('address_from', 'address_to')

    for group in groups:
    group.update(bill = bill)


    The point is to assign a specific Bill instance for each group of the orders that have the same address from and address to.

    Continue reading...

Compartilhe esta Página