首页 文章

Peewee返回所有未被外键引用的对象

提问于
浏览
0

我有坐标和天气事件的模型 . 坐标对象不引用天气事件,但每个Weather对象都有一个ForeignKeyField到Coordinate . 我想返回Weather模型中未被外键引用的所有Coordinate对象 .

我想对此有一个查询,但以下是我最接近的并说明了我想要实现的目标:

coords = Coordinate.select()
no_weather = Coordinate.select().join(Weather).where(~(Weather.coordinate << coords))

我希望我很接近,因为省略“〜”会返回与Weather对象关联的所有Coordinate对象;我只是想反过来 .

1 回答

  • 1

    有很多方法可以做到这一点 . 这是一个:

    (Coordinate
     .select()
     .join(Weather, JOIN.LEFT_OUTER)
     .group_by(Coordinate)
     .having(fn.COUNT(Weather.id) == 0))
    

    也许还有:

    (Coordinate
     .select()
     .where(~fn.EXISTS(
         Weather
         .select()
         .where(Weather.coordinate == Coordinate.id))))
    

相关问题