python - How to check for a ForeignKey that no longer exists? -


class personsite(models.model):     vps_id             = models.autofield(primary_key=true)     person             = models.foreignkey(canonperson, db_column='p_id',null=true)     site               = models.foreignkey(canonsite, db_column='s_id',null=true)  person_sites = personsite.objects.filter(person=cp) person_site in person_sites:     if person_site , person_site.site_id , person_site.site.s_id:        # crashes records 

we have problem data, personsite may point site no longer exists. in debugger can see person_site.site_id has value of 5579, id doesn't exist in database:

select * tbl_vpd_sites s_id = 5579 

hence person_site.site_id not null, yet accessing person_site.site within conditional crashes app message:

doesnotexist: canonsite matching query not exist. 

this difficult situation, can't check case bypass it.

personsite.site has null=true, makes sense have check if object exists before accessing it.

in stead of doing checks if person_site , person_site.site_id , person_site.site.s_id: can query db , filter empty sites out.

person_sites = personsite.objects.filter(person=cp).filter(site__isnull=false) 

this return personsite objects site is not null , therefore have pk.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -