Steven Spasbo
Steven Spasbo

Reputation: 646

Django - Finding all related OneToOneField objects through the foreign object

Sorry if that title isn't clear, here's what I'm trying to accomplish:

class Document(models.Model):
    processed = models.BooleanField(default=False)

class ParentClass(models.Model)
    document = models.OneToOneField(Document, on_delete=models.SET_NULL, null=True)

    class Meta:
        abstract = True

    def do_something():
        raise NotImplementedError()

class SubclassOne(ParentClass):
    # Some fields.
    def do_something(self):
        # Something specific to this subclass

class SubclassTwo(ParentClass):
    # Some other fields.
    def do_something(self):
        # Something specific to this subclass

My first thought was to try querying through the ParentClass

ParentClass.objects.filter(document__processed=False)

But that doesn't work because the parent class is abstract.

Now I have tried going through the Document object

Document.objects.filter(processed=False)

But there doesn't seem to be a way to look up the related objects through each individual Document. I'm not sure that's a good solution anyways because of the tight coupling of the ParentClass to the Document, which shouldn't need to be aware of ParentClass's implementation.

Upvotes: 0

Views: 170

Answers (2)

kamran890
kamran890

Reputation: 842

You can find all reverse related field names, and can loop over that as below:

documents = Document.objects.filter(processed=False)
reverse_related_fields = Document._meta.get_fields()

for document in documents:
    for reverse_related_field in reverse_related_fields:
        if reverse_related_field.one_to_one:
            attr = getattr(document, f"{reverse_related_field.name}_set")
            try:
                attr.get().do_something
            except Exception:
                pass

Upvotes: 1

nikoola
nikoola

Reputation: 151

ParentClass.objects.filter(document__processed=False)

This will return all Documents that have processed set to False.

Upvotes: 0

Related Questions