任意加入 Django Models

发布于 2024-11-01 17:46:50 字数 442 浏览 3 评论 0原文

假设模型 X 有一个字段 n (整数)。现在我还有一个模型 Y ,其中包含字段 nm (整数)。是否可以使用 Django ORM 选择 x (模型 X) 以便存在 y (模型 Y)对于给定的m值,xn = ynym = m

请不要建议我在两个模型之间引入 ForeignKey 关系或类似的关系。我想具体知道是否可以在不修改模型的情况下实现这一目标。在我正在处理的具体情况下,给定的关系是通用的。通用关系的反面可以是任何东西,所以根据文档,我不能在不同的模型中多次引入 GenericRelation 。

Let's say model X has a field n (an integer). Now I also have a model Y which has fields n and m (integers). Is it possible using Django ORM to select x (model X) such that there exists y (model Y) such that x.n = y.n and y.m = m for a given value of m?

Please don't advise me to introduce a ForeignKey relationship between the two models or anything like that. I'd like to know specifically if it's possible to achieve this without modifying the model. In the exact case that I'm working on, the given relationships are generic. And the opposite side of the generic relationship can be anything, so according to the docs I cannot really introduce GenericRelation multiple times in different models.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

巨坚强 2024-11-08 17:46:50

我想这可以使用 额外 QuerySet 方法。

(我没有测试过)

X.objects.extra(where=["x.n in (select y.n from y where y.m = '%s')"], params=['m_value'])

i suppose this could be achieved using extra QuerySet method.

(i didn't tested it)

X.objects.extra(where=["x.n in (select y.n from y where y.m = '%s')"], params=['m_value'])
酒中人 2024-11-08 17:46:50

您可以使用原始 sql 来执行此操作:

def my_custom_sql(m):
    from django.db import connection, transaction
    cursor = connection.cursor()

    # Data retrieval operation - no commit required

    command = """SELECT * 
      FROM tX 
INNER JOIN tY
        ON (tX.n=tY.n AND tY.m=%s)"""

    cursor.execute(command % str(m))
    rows = cursor.fetchall()

    return rows

使用 ORM,我认为您可以使用 values_listin 过滤器来执行此操作:

class X(models.Model):
    n = models.IntegerField()

class Y(models.Model):
    n = models.IntegerField()
    m = models.IntegerField()

xs = X.objects.filter(n__in=Y.objects.filter(m=m).values_list('n')).distinct()

编辑:
正如评论中所述,此方法会对数据库造成很大影响

You can do this using raw sql:

def my_custom_sql(m):
    from django.db import connection, transaction
    cursor = connection.cursor()

    # Data retrieval operation - no commit required

    command = """SELECT * 
      FROM tX 
INNER JOIN tY
        ON (tX.n=tY.n AND tY.m=%s)"""

    cursor.execute(command % str(m))
    rows = cursor.fetchall()

    return rows

using the ORM, i think you can do this using values_list and the in filter:

class X(models.Model):
    n = models.IntegerField()

class Y(models.Model):
    n = models.IntegerField()
    m = models.IntegerField()

xs = X.objects.filter(n__in=Y.objects.filter(m=m).values_list('n')).distinct()

edit:
As noted in the comments this method will hit the db a lot

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文