python - 如何在 Django 中进行连接?

标签 python django django-queryset

我有以下模型:

class Part(models.Model):
    user = models.ForeignKey(User)
    part_number = models.CharField()

class Inventory(models.Model):
    user = models.ForeignKey(User)
    part = models.ForeignKey(Part)
    stock = models.IntegerField()
    storage_location = ...

class Project(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField()

class ProjectItem(models.Model):
    project = models.ForeignKey(Project)
    part = models.ForeignKey(Part)
    quantity = models.IntegerField()

给定零件可以有多个 Inventory 对象,每个存储位置对应一个对象。给定一个 Project,我想获取所有 ProjectItem 的列表以及每个 ProjectItem< 对应的 Inventory 对象 部分。这可以通过 Django 查询实现吗?

我可以做到

for pi in ProjectItem.objects.filter(project=project):
    for inv in Inventory.objects.filter(user=user, part=pi.part)
        ...

但我不想对每个 ProjectItem 进行查询。我想做的是:

project_items = ProjectItem.objects.filter(project=project,
                                           part__inventory__user=user)

但我不知道如何获取查询中匹配的 Inventory 对象。

有什么想法吗?

编辑:让我用一个例子来澄清。始终修复Project A 和User 棉花。以下是一些表格(省略了 ProjectUser)。

项目项:

Part  Quantity
-----------------------
   X         2
   Y         1

库存:

Part  Stock  Location
---------------------
   X     91         S
   X     13         T
   Y     14         S
   Y    101         U

我想要的(以表格形式)是:

Part Quantity Stock Location
------------------------------------
   X        2    91        S
   X        2    13        T
   Y        1    14        S
   Y        1   101        U

也就是说,我只想将 ProjectItemInventory 以及 partuser 一起加入。

编辑 2:一种可能性是执行两个查询(对象、相关对象)并在 Python 中执行连接,如下所述:

http://blog.roseman.org.uk/2010/01/11/django-patterns-part-2-efficient-reverse-lookups/

与在数据库中进行联接相比,我不会称其高效,但它可能比 n+1 查询更好。

最佳答案

prefetch_related(*lookups)

返回一个查询集,该查询集将在单个批处理中自动检索每个指定查找的相关对象。

https://docs.djangoproject.com/en/1.6/ref/models/querysets/#prefetch-related

关于python - 如何在 Django 中进行连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20799595/

相关文章:

jquery - 500服务器错误,我不知道出了什么问题,ajax,django

python - 将 Pandas DF 转换为 Numpy Array 在尝试预测时会出现 # of features 错误?

python - web.py 上的 HAML/SCSS

python - 如何在PyCharm中运行 flask 外壳?

Django 在基于类的通用 ListView 中过滤子对象

Django:如何有条件地过滤外键

python - numpy 数组的条件运算

具有多个外键的 Django 内联表单

Django查询: How to order posts by amount of upvotes?

python - 我遇到了一个关于 django Queryset 的棘手问题