[Answer]-How to filter out nonexistent object that a foreign key is pointing to



I suggest that solution will help you:

r_for_date = PR.objects.filter(person__id__isnull=False,recall_dt__range = (startdate, enddate))

Besause person__id belongs to person table.

But it will be better when you define this filter in manager

class PRManager(models.Manager):
def get_queryset(self):
    return super(PRManager, self).get_queryset().filter(person__id__isnull=False)

That allows you not add person__id__isnull=False to each filter. Hope that’ll help you. Please tell me about results after you trying this.


Here is what I would do..

valid_people_ids = Person.objects.all().values_list('id', flat=True)
bad_pr_people = PR.objects.exclude(person_id__in=valid_people_ids)

Hope that helps.


Leave a comment