Django ORM: See if a model has no foreign key entry in another model

孤街浪徒 提交于 2020-01-03 08:29:49

问题


So , I have this 2 models:

class Site(models.Model):
    ...
    ...

and another one:

class SiteInfo(models.Model):
    ...
    ...
    site = models.ForeignKey(Site)

Is there a way to get the Sites that have no entry in the SiteInfo ?


回答1:


Site.objects.filter(siteinfo__isnull=True)




回答2:


There is a generic way to find the list of all reverse relations of a model.

reverse_model_array = [f.related_model for f in model._meta.get_fields() 
if f.auto_created and not f.concrete]

This will list all the models that have reference to this model(foreign key, many to many key, etc)




回答3:


I think this will working, but not so efficient:

with_no_site_info = [site for site in Site.objects.all() if site.site_infos_set.all().count() == 0]



来源:https://stackoverflow.com/questions/6094835/django-orm-see-if-a-model-has-no-foreign-key-entry-in-another-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!