How to select orphan records from a model where referential integrity is not applied?

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 the data from the spreadsheet into "Children" I need to get a list of parents who do not have children, and for this I use ...

Parent.objects.filter(children__isnull=True)

which seems to be working fine.

But since referential integrity is not applied, I also need a list of children who do not have a parent, and for this I try ...

Children.objects.filter(parent__isnull=True)

which returns an empty request, although some of them are orphans? Any pointers to the best way to achieve this will be very helpful.

By the way, I know that I can pick up orphans during the import process, but this is not very suitable for my purpose.

+3
2

, Django :

def Foo(request):
    parent_ids=Parent.objects.values('id')
    orphans=Children.objects.exclude(parent_id__in=parent_ids)
    return render_to_response('Foo.html', {'orphans':orphans})
+2

,

, ...

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})

, ?


...

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})
+1

Source: https://habr.com/ru/post/1731709/


All Articles