Django 模型外键字段匹配

发布于 2024-10-03 17:26:07 字数 783 浏览 0 评论 0原文

我有以下 Django 模型 -

class M(models.Model):
    ...
    disp_name = models.CharField(max_length=256, db_index=True)
    ...

class XX(models.Model):
    x = models.ForeignKey(User)
    y = models.ForeignKey(M, unique=True)

现在在我的views.py中,我想对 XX 中的所有项目与字段 y.disp_name 进行部分字符串匹配。

通常人们会这样做 - M.objects.filter(disp_name__istartswith='string')

但这里 MModel XX 中的外键。因此,如果我执行 XX.objects.filter(y.disp_name__istartswith='string') 我会收到错误。

另外,这也失败了 - u = User.objects.get(id=1) u.xx_​​set.filter(y.disp_name__istartswith='string')

我得到的异常是 - SyntaxError: keywords can't be an expression (, line 1)

如何做到这一点?

I have the following Django Model -

class M(models.Model):
    ...
    disp_name = models.CharField(max_length=256, db_index=True)
    ...

class XX(models.Model):
    x = models.ForeignKey(User)
    y = models.ForeignKey(M, unique=True)

Now in my views.py, I want to do a partial string match on all items in XX with the field y.disp_name.

Normally one would do this - M.objects.filter(disp_name__istartswith='string')

But here M is a foreignkey in Model XX. So if I do XX.objects.filter(y.disp_name__istartswith='string') I get an error.

Also, this too fails -
u = User.objects.get(id=1)
u.xx_set.filter(y.disp_name__istartswith='string')

Exception that I get says is - SyntaxError: keyword can't be an expression (<console>, line 1)

How to do this?

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

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

发布评论

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

评论(1

ゞ花落谁相伴 2024-10-10 17:26:07

我希望您使用了正确的字段名称,而不是 X、Y 和 M - 这真的很难理解。

但无论如何,您应该始终使用双下划线语法来遵循过滤器表达式左侧的关系:(

XX.objects.filter(y__disp_name__istartswith='string')

这样做的技术原因是 filter 的参数实际上是关键字参数到一个函数,所以它的左侧必须是一个字符串而不是一个表达式。)

I wish you had used proper field names rather than X, Y and M - it's really hard to follow.

But in any case, you should always use the double-underscore syntax to follow relations on the left hand side of the filter expression:

XX.objects.filter(y__disp_name__istartswith='string')

(The technical reason for this is that the parameters to filter are actually keyword arguments to a function, so the left-hand side of that has to be a string rather than an expression.)

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