【问题标题】:Using PostgreSQL Arrayfield as ManyToMany -like lookup?将 PostgreSQL Arrayfield 用作类似 ManyToMany 的查找?
【发布时间】:2019-10-12 21:03:13
【问题描述】:

我有两个模型:

class Authors(models.Model):
    name = models.CharField()

class Books(models.Model):
    title = models.CharField()
    author_ids = ArrayField(Integerfield())

我希望能够通过books.authors 了解这些书籍的作者。有没有办法做到这一点?我似乎找不到办法做到这一点。该数据库已经预先填充了author_ids,因此将其改造成其他内容(例如使用中间表)会很困难。

【问题讨论】:

    标签: python django postgresql django-models django-orm


    【解决方案1】:

    您可以使用结合id__in的子查询:

    author_ids = Books.objects.first().values('author_ids')
    authors = Authors.objects.filter(id__in=author_ids)
    

    如果你只评估authors,这只会命中数据库一次。如果您需要同时评估书籍和作者,那么使用联合可能是更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-21
      • 2017-08-12
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2012-06-30
      • 2014-10-16
      • 1970-01-01
      相关资源
      最近更新 更多