django - How to filter out nonexistent object that a foreign key is pointing to -


i have model has relationship model through foreign key called person. model looks like:

class pr(models.model):     p_keyid   = models.integerfield(primary_key=true)     r_no      = models.integerfield(null=true, blank=true)     person    = models.foreignkey('person.person', db_column = 'person_no')     recall_dt = models.datetimefield(null=true, blank=true)      class meta:         managed  = false         db_table = 'person_r' 

note "managed" meta false (and not table created).

sometimes there person_no value in person_r table not exist. example, pr.person has value of 232. however, person id 232 not exist (foreign key pointing object not exist). how can filter out such bad pr instances?

in view have this:

 r_for_date = pr.objects.filter(recall_dt__range = (startdate, enddate)  

and want r_for_date contain records person attribute not exist (in example above, record person id of 232 should not show up).

i suggest solution you:

r_for_date = pr.objects.filter(person__id__isnull=false,recall_dt__range = (startdate, enddate))

besause person__id belongs person table.

but better when define filter in manager

class prmanager(models.manager): def get_queryset(self):     return super(prmanager, self).get_queryset().filter(person__id__isnull=false) 

that allows not add person__id__isnull=false each filter. hope that'll you. please tell me results after trying this.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -