3

I want to perform a filter on a model and return all objects that have a specific attribute.

model.objects.filter(hasattr(model, 'attrname'))

This obviously doesn't work, but not sure how to efficiently implement something siilar.

Thanks

EDIT

An example of where I would use this is when a model is inherited from another

class model1(models.Model):
    ...

class model2(model1):
    ...

if I do a model1.objects.all() each of the returned objects that are in model2 will have an extra attribute

3 Answers 3

3

If the models are related, you can the isnull in the filter.

model1.objects.filter('related_name__field_name__isnull=False)

where related name is in for the foreign key in model2

For Example: class Owner(models.Model): user = models.CharField(max_length=10)

class Car(models.Model):
    car_type = models.CharField(max_length=10)
    owner = models.ForeignKey(Owner, related_name='cars', 
        on_delete=models.CASCADE)

For owners with cars: owners = Owner.objects.filter(cars__id__isnull=False)

2
  • Did you mean "use isnull in the filter?"
    – Ann Kilzer
    Dec 18, 2019 at 14:47
  • @AnnKilzer yes, 'owners = Owner.objects.filter(cars__id__isnull=False)' Dec 19, 2019 at 6:49
0

I just put it in a:

try:
    ....
except AttributeError:
    ....
0

The way I did it was to suppress the FieldError exception:

from django.core.exceptions import FieldError
from contextlib import suppress

with suppress(FieldError):
    model.objects.filter(field_in_other_class=value)

hope that helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.