[Django]-Django filter query using hasattr (or something like it)

0👍

I just put it in a:

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

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)

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

Leave a comment