[Answered ]-Django query self referencing queryset

1👍

You can filter with:

Thing.objects.filter(copied_from=None)

This will thus retrieve all Things where the copied_from is None.

If you want to retrieve all Things that are no copies, and have not been copied from, you can work with:

Thing.objects.filter(copied_from=None, copies=None)

or if you want to retrieve Things for which no Thing exists that is a copy from that, you can work with:

Thing.objects.filter(copies=None)

This works since we perform a LEFT OUTER JOIN on the Thing table, and only retrieve Things fro which the LEFT OUTER JOIN is NULL.

Leave a comment