views:

32

answers:

1

Given the following models implemented in sqlite3

class Parent(models.Model):
    pass

class Children(models.Model):
    parent=models.ForeignKey(Parent,primary_key=True)

After importing data from a spreadsheet into Children I need to get a list of Parents having no children and for this I'm using...

Parent.objects.filter(children__isnull=True)

which seems to work fine.

But because referential integrity is not enforced I also need a list of Children having no Parent and for this I'm trying...

Children.objects.filter(parent__isnull=True)

which returns an empty queryset even though some are orphans? Any pointers as to the best way of achieving this would be greatly appreciated.

By the way, I know I can pick up the orphans during the import process but this would not suit my purpose so well.

+1  A: 

No answers yet so here's my attempt to answer my own question

Here is an ugly solution that works...

def Foo(request):
    orphans=[]
    for child in Children.objects.all():
        try:
            if child.parent:
                pass
        except Parent.DoesNotExist:
            orphans.append(child)
    return render_to_response('Foo.html',{'orphans':orphans})

Hopefully there is a better way?


Update improved method...

def Foo(request):
    parent_id_list=[row.pk for row in Parent.objects.all()]
    orphans=Children.objects.exclude(pk__in=parent_id_list)
    return render_to_response('Foo.html',{'orphans':orphans})
FxFocus