gpt4 book ai didi

python - 外键问题

转载 作者:太空宇宙 更新时间:2023-11-04 11:04:17 25 4
gpt4 key购买 nike

假设您有这个模型:

class Category(models.Model):
node_id = models.IntegerField(primary_key = True)
type_id = models.IntegerField(max_length = 20)
parent_id = models.IntegerField(max_length = 20)
sort_order = models.IntegerField(max_length = 20)
name = models.CharField(max_length = 45)
lft = models.IntegerField(max_length = 20)
rgt = models.IntegerField(max_length = 20)
depth = models.IntegerField(max_length = 20)
added_on = models.DateTimeField(auto_now = True)
updated_on = models.DateTimeField(auto_now = True)
status = models.IntegerField(max_length = 20)
node = models.ForeignKey(Category_info, verbose_name = 'Category_info', to_field = 'node_id'

重要的部分是外键。当我尝试时:

Category.objects.filter(type_id = 15, parent_id = offset, status = 1)

我收到一个错误,返回的类别超过类别,这很好,因为它应该返回多个类别。但我想通过另一个字段过滤结果,该字段是类型 id(来自第二个模型)

这里是:

class Category_info(models.Model):
objtree_label_id = models.AutoField(primary_key = True)
node_id = models.IntegerField(unique = True)
language_id = models.IntegerField()
label = models.CharField(max_length = 255)
type_id = models.IntegerField()

type_id 可以是 1 - 5 中的任何数字。我拼命地尝试只获得一个结果,其中 type_id 为数字 1。

这是我想要的sql:

SELECT c.*, ci.*
FROM category c
JOIN category_info ci ON (c.node_id = ci.node_id)
WHERE c.type_id = 15 AND c.parent_id = 50 AND ci.type_id = 1

非常感谢任何帮助。

问候

最佳答案

要过滤相关表中的字段,请使用双下划线表示法。要获取相关 Category_info 对象的 type_id 为 15 的所有 Category 对象,请使用:

Category.objects.filter(node__type_id=15)

Django 然后会自动理解您指的是 node 相关的任何表上的 type_id 字段。

关于python - 外键问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2766637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com