Django 模型外键字段匹配
我有以下 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')
但这里 M
是 Model 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 (
如何做到这一点?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我希望您使用了正确的字段名称,而不是 X、Y 和 M - 这真的很难理解。
但无论如何,您应该始终使用双下划线语法来遵循过滤器表达式左侧的关系:(
这样做的技术原因是
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:
(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.)