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)
- [Django]-Django project /admin Site matching query does not exist
- [Django]-May not set both `read_only` and `write_only`
- [Django]-How to fix "cannot unpack non-iterable NoneType object" error in django admin whilst using custom user model
- [Django]-How to set MaxDate and MinDate of a SelectDateWidget in Django?
- [Django]-Django – Keeping the original method's work and add new custom validation
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
Source:stackexchange.com