问题
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