'What queryset should I do to select all One-to-one relations that are broken?

I have this 2 models :

class Asset(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    ... some other fields ...

class AssetConstructorData(models.Model):
    asset = models.OneToOneField(
        Asset,
        on_delete=models.CASCADE,
        primary_key=True,
        related_name='constructor_data',
    )
    ... some other fields ...

For some historical reason, I have some One-to-one which are broken : some AssetConstructorData object has not their corresponding Asset object. I would like to delete all AssetConstructorData objects that are broken.

Actually I have done :

for cd in AssetConstructorData.objects.all():
    try:
        cd.asset
    except Asset.DoesNotExist:
        cd.delete()

Which is definitively not optimized : Is that possible to make a queryset that selects all broken relations ?

I tried with .filter(asset=None) and .filter(asset__isnull=True) but it does not work.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source