django - 如果第二个表中存在过滤行,则注释 django 查询

标签 django postgresql

我有两个表(类似于下面的表):

class Piece(models.Model):
    cost = models.IntegerField(default=50)
    piece = models.CharField(max_length=256)

class User_Piece (models.Model):
    user = models.ForeignKey(User)
    piece = models.ForeignKey(Piece)

我想做一个返回 Piece 中的所有项目的查询,但是用登录用户是否拥有该部分来注释每一行(所以 User_Piece< 中存在一行 其中用户是登录用户)。

我试过:

pieces = Piece.objects.annotate(owned=Count('user_piece__id'))

但对于任何 用户拥有的任何作品,它的计数 > 0。我不确定我在哪里/如何设置 user_piece 必须具有我想要的指定用户的条件。如果我过滤 user__piece__user=user,那么我不会从 Piece 中获取所有行,而只会获取那些拥有的行。

最佳答案

您可以使用 Exist 子查询包装器:

from django.db.models import Exists, OuterRef

subquery = User_Piece.objects.filter(user=user, piece=OuterRef('pk'))
Piece.objects.annotate(owned=Exists(subquery))

https://docs.djangoproject.com/en/dev/ref/models/expressions/#exists-subqueries

关于django - 如果第二个表中存在过滤行,则注释 django 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30339449/

相关文章:

sql - 如何让查询更快?

django - 日期输入 : how to show placeholder

django - 通过 URL 传递对象数据

javascript - AJAX 请求复制整个页面

python - 如何将图像渲染到模板?

postgresql - 从 SQLAlchemy 中的 IntegrityError 中恢复

python - Django 多站点

sql - 在不同的表上插入/更新条件

sql - 找不到 SKU 时返回 0 数量

ruby-on-rails - DatabaseCleaner.clean_with( :truncate) does not reset auto incremented id