StaticName
StaticName

Reputation: 295

Django: order set queries

I have following 3 models

class Product(models.Model):

    name = models.CharField(
        blank=False,
        max_length=256
    )


class TaskGroup(models.Model):
    name = models.CharField(
        blank=False,
        max_length=256
    )

    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
        null=False,
        blank=True
    )


class Task(models.Model):
    name = models.CharField(
        blank=False,
        max_length=256
    )

    task_group = models.ForeignKey(
        TaskGroup,
        on_delete=models.CASCADE,
        null=False,
        blank=True
    )
    
    execute_at = models.DateField(
        blank=True
        null=True,
    )

I want to get task groups for a product and order the tasks for each task group by execute_at. I can get all the task groups and all the tasks for a product by

product = Product.objects.first()
task_groups = product.taskgroup_set.all()

task_groups contains all the groups and all tasks for each group. I can also do something like task_groups[0].task_set.all().order_by('execute_at'). I don't know how to put together these queries and order the tasks of each group by execute_at in a single query.

Upvotes: 0

Views: 194

Answers (1)

Abdul Aziz Barkat
Abdul Aziz Barkat

Reputation: 21787

You can use Prefetch() objects and specify the queryset for the prefetched objects (This is also better for efficiency as lesser amount of queries would be made to the database):

from django.db.models import Prefetch


product = Product.objects.filter(pk=some_pk).prefetch_related(
    Prefetch(
        'taskgroup_set__task_set',
         queryset=Task.objects.order_by('execute_at')
    )
).get() # Change `.filter(pk=some_pk)` as per your implementation

Upvotes: 1

Related Questions