views:

31

answers:

1

Hi, I have a model like so:

class Activity(models.Model):  
    title = models.CharField(max_length=200)
    summary = models.TextField(null=True, blank=True)  
    tasks = models.ManyToManyField('self', symmetrical=False, null=True, blank=True)  

It works like this, an activity can be linked to itself and the parent activity is called an 'Activity' and the child activity/activities will be called 'Task/Tasks'

How do I filter the model to get all the 'Activities' and How do I filter the model to get all the 'Tasks' ?

Thanks for all the help.

A: 

Here you go:

from django.db.models import Count

annotated_qs = Activity.objects.annotate(num_tasks=Count(tasks))

activities = annotated_qs.objects.filter(num_tasks=0)
tasks = annotated_qs.objects.filter(num_tasks__gt=0)

:)

You could do it with better performance without annotation, if you use __is_null=True, but I can't recall or quick google it's syntax right now.

Lakshman Prasad
Doest quite work how I wanted it to. Activities can have 0 or more 'tasks' and tasks can also have 0 or more 'subtasks' as well. All this happens within the same table.An activity is only an activity if it is not a 'child' elementA task is a task if it is a 'child' element of an Activity.I hope I am making sense! I know this can be done, but don't know how.
ninja123
actually it worked after doing some tweeks... Changed it to:annotated_qs = Activity.objects.annotate(num_parent=Count('activity')) activities = annotated_qs.filter(num_parent=0) tasks = annotated_qs.filter(num_parent__gt=0)
ninja123