class AModel(models.Model)
some = CharField()
class BModel(models.Model)
some = CharField()
a_model = models.ForeignKey(AModel, models.CASCADE, related_name="b_models")
class CModel(models.Model)
some = CharField()
a_model = models.ForeignKey(AModel, models.CASCADE, related_name="c_models")
# Вот теперь мне нужно найти все AModel, у которых
a_model.b_models.all().exists() == False and
a_model.c_models.all().exists() == False
也就是说,这些模型尚未绑定到的那些。
如何提出这样的要求?谢谢你。
我会这样做:
isnull用于检测丢失的外键。链接到文档。
distinct用于排除 AModel 的重复 - 如果
isnull=True对特定 AModel 有多个外部引用,则它们将被排除。链接到文档。PS:我在我的大型项目中检查了这段代码的性能。